mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit dfd979ec1e
This commit is contained in:
1 parent
d8adf3c1b6
commit
968061e89a
111 files changed
+19955
-292
No files matched your search
@@ -81,11 +81,11 @@ Authorization: Bearer <token>
|
||||
| Query parameter | Meaning |
|
||||
| --- | --- |
|
||||
| `libraryId` | Optional. The Id of a library to restrict the history to. It must be a non-empty Guid. |
|
||||
| `mediaKind` | Optional. A media kind to restrict the history to. `None` is rejected. |
|
||||
| `mediaKind` | Optional. The name of a media kind to restrict the history to, matched case insensitively. Only member names are accepted, so a numeric value is rejected even when it is a defined enumeration value. `None` is rejected. |
|
||||
| `currentPage` | Optional. The one based page of distinct media items to return. |
|
||||
| `perPage` | Optional. The number of distinct media items per page. |
|
||||
| `fromUtc` | Optional. The inclusive start of the history date range. |
|
||||
| `toUtc` | Optional. The inclusive end of the history date range. It must not be before `fromUtc`. |
|
||||
| `fromUtc` | Optional. The inclusive start of the history date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. |
|
||||
| `toUtc` | Optional. The inclusive end of the history date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. It must not be before `fromUtc`. |
|
||||
|
||||
The same query parameters apply to the per-user route. The route user is the target, and the access policy decides whether the caller may read it.
|
||||
|
||||
@@ -198,9 +198,9 @@ Authorization: Bearer <token>
|
||||
| Query parameter | Meaning |
|
||||
| --- | --- |
|
||||
| `libraryId` | Optional. The Id of a library to restrict the statistics to. It must be a non-empty Guid. |
|
||||
| `mediaKind` | Optional. A media kind to restrict the statistics to. `None` is rejected. |
|
||||
| `fromUtc` | Optional. The inclusive start of the date range. |
|
||||
| `toUtc` | Optional. The inclusive end of the date range. It must not be before `fromUtc`. |
|
||||
| `mediaKind` | Optional. The name of a media kind to restrict the statistics to, matched case insensitively. Only member names are accepted, so a numeric value is rejected even when it is a defined enumeration value. `None` is rejected. |
|
||||
| `fromUtc` | Optional. The inclusive start of the date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. |
|
||||
| `toUtc` | Optional. The inclusive end of the date range, in UTC. A trailing zone designator is honored and converted to UTC, while a value without one is interpreted as UTC. It must not be before `fromUtc`. |
|
||||
|
||||
#### Get Consumption Statistics Response
|
||||
|
||||
@@ -585,9 +585,9 @@ A request that fails validation is rejected with `422 Unprocessable Entity` and
|
||||
| `MediaItemIdCannotBeEmpty` | Delete item history | The `mediaItemId` route value is the empty Guid. |
|
||||
| `LibraryIdCannotBeEmpty` | Statistics filters, delete item history, clear resume points | A supplied library Id is not a non-empty Guid. |
|
||||
| `UnsupportedMediaKind` | Statistics filters, delete item history | The supplied kind is `None` or is not a defined media kind. Omitting `mediaKind` is valid on the statistics filters. |
|
||||
| `ConsumptionDateRangeIsInvalid` | Statistics filters | `fromUtc` is after `toUtc`. |
|
||||
| `ConsumptionDateRangeIsInvalid` | Statistics filters | A date bound is not a valid date, or `fromUtc` is after `toUtc`. |
|
||||
|
||||
A value that cannot be bound to the request type, such as a malformed route Id on delete item history or an unknown media kind name on a query filter, is rejected by the framework before these validators run.
|
||||
A value that cannot be bound to the request type, such as a malformed route Id on delete item history, is rejected by the framework before these validators run. Media kind query filters are carried as text, so an unknown name reaches the validator and is reported as `UnsupportedMediaKind`.
|
||||
|
||||
### Concurrency
|
||||
|
||||
|
||||
+8
-1
@@ -27,6 +27,13 @@ public static class GetMostConsumedRequestMapping
|
||||
PerPage = request.PerPage ?? 50
|
||||
};
|
||||
|
||||
return new GetMostConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, request.FromUtc, request.ToUtc, paginationData);
|
||||
return new GetMostConsumedQuery(
|
||||
targetUserId,
|
||||
request.LibraryId,
|
||||
request.MediaKind,
|
||||
request.FromUtc,
|
||||
request.ToUtc,
|
||||
paginationData
|
||||
);
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -27,6 +27,13 @@ public static class GetRecentlyConsumedRequestMapping
|
||||
PerPage = request.PerPage ?? 50
|
||||
};
|
||||
|
||||
return new GetRecentlyConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, request.FromUtc, request.ToUtc, paginationData);
|
||||
return new GetRecentlyConsumedQuery(
|
||||
targetUserId,
|
||||
request.LibraryId,
|
||||
request.MediaKind,
|
||||
request.FromUtc,
|
||||
request.ToUtc,
|
||||
paginationData
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
#endregion
|
||||
|
||||
@@ -258,6 +259,23 @@ public static class ValidatorUtilities
|
||||
return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures a textual enum value is either <see langword="null"/> or the name of a defined member of the specified
|
||||
/// enumeration type.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only the member names of the enumeration are accepted, so a numeric value is rejected even when it is a defined member. A
|
||||
/// <see langword="null"/> value represents an omitted optional filter and passes.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
|
||||
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
|
||||
/// <param name="ruleBuilder">The rule builder instance.</param>
|
||||
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
|
||||
public static IRuleBuilder<TRequest, string?> IsInEnum<TRequest, TEnum>(this IRuleBuilder<TRequest, string?> ruleBuilder) where TEnum : struct, Enum
|
||||
{
|
||||
return ruleBuilder.Must(value => value is null || Enum.GetNames<TEnum>().Contains(value, StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a validation rule that ensures the string property does not exceed the specified maximum length.
|
||||
/// </summary>
|
||||
|
||||
+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.Queries.GetAllUsersConsumptio
|
||||
/// Query for getting the consumption statistics of every user.
|
||||
/// </summary>
|
||||
/// <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, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, or <see langword="null"/> when the range has no end.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetAllUsersConsumptionStatisticsQuery(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
) : IQuery;
|
||||
+5
-1
@@ -14,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.V
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -78,10 +79,13 @@ public class GetAllUsersConsumptionStatisticsQueryHandler : IQueryHandler<GetAll
|
||||
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);
|
||||
|
||||
// This is the only statistics query that loads the records of every user, and it is reachable only through the admin check above.
|
||||
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
|
||||
.GetForAllUsersAsync(libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
|
||||
.GetForAllUsersAsync(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.GetAllUsersConsumptionStatistics;
|
||||
@@ -23,18 +24,42 @@ public class GetAllUsersConsumptionStatisticsQueryValidator : AbstractValidator<
|
||||
(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<GetAllUsersConsumptionStatisticsQuery, 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,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.GetConsumptionStatist
|
||||
/// </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, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, or <see langword="null"/> when the range has no end.</param>
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
|
||||
public record GetConsumptionStatisticsQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
) : IQuery;
|
||||
+5
-1
@@ -15,6 +15,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.V
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -81,10 +82,13 @@ public class GetConsumptionStatisticsQueryHandler : IQueryHandler<GetConsumption
|
||||
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);
|
||||
|
||||
// The handlers aggregate the records themselves; the repository only binds the filters and returns the records without tracking.
|
||||
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.GetConsumptionStatistics;
|
||||
@@ -29,18 +30,42 @@ public class GetConsumptionStatisticsQueryValidator : AbstractValidator<GetConsu
|
||||
(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<GetConsumptionStatisticsQuery, 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,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -13,16 +11,16 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
|
||||
/// </summary>
|
||||
/// <param name="TargetUserId">The Id of the user whose history is retrieved, or <see langword="null"/> for the current user.</param>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the history to, or <see langword="null"/> for every library.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the history 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 history to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range, in UTC, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, or <see langword="null"/> when the range has no end.</param>
|
||||
/// <param name="PaginationData">The object containing the requested pagination data. When <see langword="null"/>, every matching item is returned; when present, its requested page is returned.</param>
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
|
||||
public record GetMostConsumedQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc,
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+5
-1
@@ -25,6 +25,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -91,9 +92,12 @@ public class GetMostConsumedQueryHandler : IQueryHandler<GetMostConsumedQuery, R
|
||||
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.GetMostConsumed;
|
||||
@@ -29,18 +30,42 @@ public class GetMostConsumedQueryValidator : AbstractValidator<GetMostConsumedQu
|
||||
(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<GetMostConsumedQuery, 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,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -13,16 +11,16 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
|
||||
/// </summary>
|
||||
/// <param name="TargetUserId">The Id of the user whose history is retrieved, or <see langword="null"/> for the current user.</param>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the history to, or <see langword="null"/> for every library.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the history 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 history to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range, in UTC, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, or <see langword="null"/> when the range has no end.</param>
|
||||
/// <param name="PaginationData">The object containing the requested pagination data. When <see langword="null"/>, every matching item is returned; when present, its requested page is returned.</param>
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
|
||||
public record GetRecentlyConsumedQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc,
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+5
-1
@@ -25,6 +25,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -91,9 +92,12 @@ public class GetRecentlyConsumedQueryHandler : IQueryHandler<GetRecentlyConsumed
|
||||
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.GetRecentlyConsumed;
|
||||
@@ -29,18 +30,42 @@ public class GetRecentlyConsumedQueryValidator : AbstractValidator<GetRecentlyCo
|
||||
(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<GetRecentlyConsumedQuery, 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,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.GetTagConsumption;
|
||||
/// </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, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, or <see langword="null"/> when the range has no end.</param>
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
|
||||
public record GetTagConsumptionQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
) : IQuery;
|
||||
+5
-1
@@ -17,6 +17,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -83,9 +84,12 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
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.GetTagConsumption;
|
||||
@@ -29,18 +30,42 @@ public class GetTagConsumptionQueryValidator : AbstractValidator<GetTagConsumpti
|
||||
(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<GetTagConsumptionQuery, 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
|
||||
|
||||
@@ -10,13 +8,13 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
|
||||
/// Represents a request for getting the consumption statistics of every 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 GetAllUsersConsumptionStatisticsRequest(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
);
|
||||
@@ -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 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 GetConsumptionStatisticsRequest(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
);
|
||||
@@ -1,6 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -10,17 +8,17 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
|
||||
/// Represents a request for getting a window of the most consumed media items of a user.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the history to. Optional.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the history to. Optional.</param>
|
||||
/// <param name="MediaKind">The name of the kind of media to restrict the history to. Optional.</param>
|
||||
/// <param name="CurrentPage">The one based page of media items to return. Optional.</param>
|
||||
/// <param name="PerPage">The number of media items per page. 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="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}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public sealed record GetMostConsumedRequest(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
string? MediaKind,
|
||||
int? CurrentPage,
|
||||
int? PerPage,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
);
|
||||
@@ -1,6 +1,4 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -10,17 +8,17 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
|
||||
/// Represents a request for getting a window of the recently consumed media items of a user.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the history to. Optional.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the history to. Optional.</param>
|
||||
/// <param name="MediaKind">The name of the kind of media to restrict the history to. Optional.</param>
|
||||
/// <param name="CurrentPage">The one based page of media items to return. Optional.</param>
|
||||
/// <param name="PerPage">The number of media items per page. 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="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}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public sealed record GetRecentlyConsumedRequest(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
string? MediaKind,
|
||||
int? CurrentPage,
|
||||
int? PerPage,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
);
|
||||
@@ -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 tags 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 GetTagConsumptionRequest(
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
string? MediaKind,
|
||||
string? FromUtc,
|
||||
string? ToUtc
|
||||
);
|
||||
+3
-3
@@ -27,12 +27,12 @@ public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary<GetAllUse
|
||||
ExampleRequest = new GetAllUsersConsumptionStatisticsRequest(
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
|
||||
|
||||
|
||||
+3
-3
@@ -27,12 +27,12 @@ public class GetConsumptionStatisticsEndpointSummary : Summary<GetConsumptionSta
|
||||
ExampleRequest = new GetConsumptionStatisticsRequest(
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
|
||||
|
||||
|
||||
+3
-3
@@ -27,13 +27,13 @@ public class GetUserConsumptionStatisticsEndpointSummary : Summary<GetUserConsum
|
||||
ExampleRequest = new GetConsumptionStatisticsRequest(
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
|
||||
|
||||
|
||||
+4
-4
@@ -27,15 +27,15 @@ public class GetMostConsumedEndpointSummary : Summary<GetMostConsumedEndpoint, G
|
||||
|
||||
ExampleRequest = new GetMostConsumedRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: MediaKind.MusicTrack,
|
||||
MediaKind: nameof(MediaKind.MusicTrack),
|
||||
CurrentPage: 1,
|
||||
PerPage: 50,
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
|
||||
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
|
||||
+4
-4
@@ -27,16 +27,16 @@ public class GetUserMostConsumedEndpointSummary : Summary<GetUserMostConsumedEnd
|
||||
|
||||
ExampleRequest = new GetMostConsumedRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: MediaKind.MusicTrack,
|
||||
MediaKind: nameof(MediaKind.MusicTrack),
|
||||
CurrentPage: 1,
|
||||
PerPage: 50,
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves.";
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
|
||||
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
|
||||
+4
-4
@@ -27,15 +27,15 @@ public class GetRecentlyConsumedEndpointSummary : Summary<GetRecentlyConsumedEnd
|
||||
|
||||
ExampleRequest = new GetRecentlyConsumedRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: MediaKind.MusicTrack,
|
||||
MediaKind: nameof(MediaKind.MusicTrack),
|
||||
CurrentPage: 1,
|
||||
PerPage: 50,
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
|
||||
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
|
||||
+4
-4
@@ -27,16 +27,16 @@ public class GetUserRecentlyConsumedEndpointSummary : Summary<GetUserRecentlyCon
|
||||
|
||||
ExampleRequest = new GetRecentlyConsumedRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: MediaKind.MusicTrack,
|
||||
MediaKind: nameof(MediaKind.MusicTrack),
|
||||
CurrentPage: 1,
|
||||
PerPage: 50,
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
Params["userId"] = "The Id of the user whose history is retrieved. An Admin can name any user; a regular user can only name themselves.";
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the history to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
|
||||
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
|
||||
+3
-3
@@ -26,12 +26,12 @@ public class GetTagConsumptionEndpointSummary : Summary<GetTagConsumptionEndpoin
|
||||
ExampleRequest = new GetTagConsumptionRequest(
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
|
||||
|
||||
|
||||
+3
-3
@@ -26,13 +26,13 @@ public class GetUserTagConsumptionEndpointSummary : Summary<GetUserTagConsumptio
|
||||
ExampleRequest = new GetTagConsumptionRequest(
|
||||
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:00Z",
|
||||
ToUtc: "2026-10-31T23:59:59Z"
|
||||
);
|
||||
|
||||
Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
|
||||
RequestParam(request => request.MediaKind, "The name of the kind of media to restrict the statistics to. Optional. Only the member names of the media kind enumeration are accepted.");
|
||||
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
|
||||
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
|
||||
|
||||
|
||||
+2
-1
@@ -35,4 +35,5 @@ public sealed record ValidatorUtilitiesTestRequest(
|
||||
int InclusiveIntValue,
|
||||
int? InclusiveNullableIntValue,
|
||||
string? EqualValue,
|
||||
string? EqualComparisonValue);
|
||||
string? EqualComparisonValue,
|
||||
string? TextualEnumValue);
|
||||
+5
-2
@@ -44,6 +44,7 @@ public class ValidatorUtilitiesTestRequestFixture
|
||||
/// <param name="inclusiveNullableIntValue">Optional. The nullable integer value that must be between 1 and 10.</param>
|
||||
/// <param name="equalValue">Optional. The value that must equal the comparison value.</param>
|
||||
/// <param name="equalComparisonValue">Optional. The comparison value.</param>
|
||||
/// <param name="textualEnumValue">Optional. The textual enum value that must be a member name of the test enumeration.</param>
|
||||
/// <returns>A configured <see cref="ValidatorUtilitiesTestRequest"/> instance.</returns>
|
||||
public ValidatorUtilitiesTestRequest Create(
|
||||
int? intValue = null,
|
||||
@@ -70,7 +71,8 @@ public class ValidatorUtilitiesTestRequestFixture
|
||||
int? inclusiveIntValue = null,
|
||||
int? inclusiveNullableIntValue = null,
|
||||
string? equalValue = null,
|
||||
string? equalComparisonValue = null)
|
||||
string? equalComparisonValue = null,
|
||||
string? textualEnumValue = null)
|
||||
{
|
||||
string resolvedPattern = patternValue ?? ValidPattern;
|
||||
return new Faker<ValidatorUtilitiesTestRequest>()
|
||||
@@ -99,7 +101,8 @@ public class ValidatorUtilitiesTestRequestFixture
|
||||
InclusiveIntValue: inclusiveIntValue ?? f.Random.Int(1, 10),
|
||||
InclusiveNullableIntValue: inclusiveNullableIntValue ?? f.Random.Int(1, 10),
|
||||
EqualValue: equalValue ?? "same",
|
||||
EqualComparisonValue: equalComparisonValue ?? "same"))
|
||||
EqualComparisonValue: equalComparisonValue ?? "same",
|
||||
TextualEnumValue: textualEnumValue ?? f.PickRandom<ValidatorUtilitiesTestEnum>().ToString()))
|
||||
.Generate();
|
||||
}
|
||||
|
||||
|
||||
+10
-11
@@ -4,6 +4,7 @@ using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionSta
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -33,9 +34,9 @@ public class GetAllUsersConsumptionStatisticsQueryFixture
|
||||
/// Creates a random valid <see cref="GetAllUsersConsumptionStatisticsQuery"/>.
|
||||
/// </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 kind of media to restrict the statistics to. Defaults to a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded moment in the past.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded moment after the start.</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, 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 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>
|
||||
@@ -43,22 +44,20 @@ public class GetAllUsersConsumptionStatisticsQueryFixture
|
||||
/// <returns>The created <see cref="GetAllUsersConsumptionStatisticsQuery"/>.</returns>
|
||||
public GetAllUsersConsumptionStatisticsQuery Create(
|
||||
string? libraryId = null,
|
||||
MediaKind? mediaKind = null,
|
||||
DateTime? fromUtc = null,
|
||||
DateTime? toUtc = null,
|
||||
string? mediaKind = null,
|
||||
string? fromUtc = null,
|
||||
string? toUtc = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeMediaKind = true,
|
||||
bool includeFromUtc = true,
|
||||
bool includeToUtc = true)
|
||||
{
|
||||
DateTime resolvedFromUtc = fromUtc ?? (toUtc.HasValue
|
||||
? toUtc.Value.AddDays(-_faker.Random.Int(1, 30))
|
||||
: DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)));
|
||||
DateTime resolvedToUtc = toUtc ?? resolvedFromUtc.AddDays(_faker.Random.Int(1, 30));
|
||||
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 GetAllUsersConsumptionStatisticsQuery(
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds) : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null);
|
||||
}
|
||||
|
||||
+10
-11
@@ -4,6 +4,7 @@ using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -34,9 +35,9 @@ public class GetConsumptionStatisticsQueryFixture
|
||||
/// </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 kind of media to restrict the statistics to. Defaults to a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded moment in the past.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded moment after the start.</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, 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 should be included, or forced to <see langword="null"/>.</param>
|
||||
@@ -46,24 +47,22 @@ public class GetConsumptionStatisticsQueryFixture
|
||||
public GetConsumptionStatisticsQuery Create(
|
||||
string? targetUserId = null,
|
||||
string? libraryId = null,
|
||||
MediaKind? mediaKind = null,
|
||||
DateTime? fromUtc = null,
|
||||
DateTime? toUtc = 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)
|
||||
{
|
||||
DateTime resolvedFromUtc = fromUtc ?? (toUtc.HasValue
|
||||
? toUtc.Value.AddDays(-_faker.Random.Int(1, 30))
|
||||
: DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)));
|
||||
DateTime resolvedToUtc = toUtc ?? resolvedFromUtc.AddDays(_faker.Random.Int(1, 30));
|
||||
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 GetConsumptionStatisticsQuery(
|
||||
includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds) : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null);
|
||||
}
|
||||
|
||||
+10
-11
@@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -37,9 +38,9 @@ public class GetMostConsumedQueryFixture
|
||||
/// </summary>
|
||||
/// <param name="targetUserId">Optional. The Id of the user whose history is retrieved. Defaults to a random Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the history to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of media to restrict the history to. Defaults to a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded moment in the past.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded moment after the start.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the history 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, as a text value.</param>
|
||||
/// <param name="paginationData">Optional. The requested pagination data. Defaults to a random page when it is included.</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>
|
||||
@@ -51,9 +52,9 @@ public class GetMostConsumedQueryFixture
|
||||
public GetMostConsumedQuery Create(
|
||||
string? targetUserId = null,
|
||||
string? libraryId = null,
|
||||
MediaKind? mediaKind = null,
|
||||
DateTime? fromUtc = null,
|
||||
DateTime? toUtc = null,
|
||||
string? mediaKind = null,
|
||||
string? fromUtc = null,
|
||||
string? toUtc = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
bool includeTargetUserId = true,
|
||||
bool includeLibraryId = true,
|
||||
@@ -62,15 +63,13 @@ public class GetMostConsumedQueryFixture
|
||||
bool includeToUtc = true,
|
||||
bool includePaginationData = false)
|
||||
{
|
||||
DateTime resolvedFromUtc = fromUtc ?? (toUtc.HasValue
|
||||
? toUtc.Value.AddDays(-_faker.Random.Int(1, 30))
|
||||
: DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)));
|
||||
DateTime resolvedToUtc = toUtc ?? resolvedFromUtc.AddDays(_faker.Random.Int(1, 30));
|
||||
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 GetMostConsumedQuery(
|
||||
includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds) : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null,
|
||||
includePaginationData ? paginationData ?? _paginationDataDtoFixture.Create() : null);
|
||||
|
||||
+10
-11
@@ -6,6 +6,7 @@ using Lumina.Application.Fixtures.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -37,9 +38,9 @@ public class GetRecentlyConsumedQueryFixture
|
||||
/// </summary>
|
||||
/// <param name="targetUserId">Optional. The Id of the user whose history is retrieved. Defaults to a random Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the history to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The kind of media to restrict the history to. Defaults to a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded moment in the past.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded moment after the start.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the history 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, as a text value.</param>
|
||||
/// <param name="paginationData">Optional. The requested pagination data. Defaults to a random page when it is included.</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>
|
||||
@@ -51,9 +52,9 @@ public class GetRecentlyConsumedQueryFixture
|
||||
public GetRecentlyConsumedQuery Create(
|
||||
string? targetUserId = null,
|
||||
string? libraryId = null,
|
||||
MediaKind? mediaKind = null,
|
||||
DateTime? fromUtc = null,
|
||||
DateTime? toUtc = null,
|
||||
string? mediaKind = null,
|
||||
string? fromUtc = null,
|
||||
string? toUtc = null,
|
||||
PaginationDataDto? paginationData = null,
|
||||
bool includeTargetUserId = true,
|
||||
bool includeLibraryId = true,
|
||||
@@ -62,15 +63,13 @@ public class GetRecentlyConsumedQueryFixture
|
||||
bool includeToUtc = true,
|
||||
bool includePaginationData = false)
|
||||
{
|
||||
DateTime resolvedFromUtc = fromUtc ?? (toUtc.HasValue
|
||||
? toUtc.Value.AddDays(-_faker.Random.Int(1, 30))
|
||||
: DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)));
|
||||
DateTime resolvedToUtc = toUtc ?? resolvedFromUtc.AddDays(_faker.Random.Int(1, 30));
|
||||
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 GetRecentlyConsumedQuery(
|
||||
includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds) : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null,
|
||||
includePaginationData ? paginationData ?? _paginationDataDtoFixture.Create() : null);
|
||||
|
||||
+10
-11
@@ -4,6 +4,7 @@ using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
@@ -34,9 +35,9 @@ public class GetTagConsumptionQueryFixture
|
||||
/// </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 kind of media to restrict the statistics to. Defaults to a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded moment in the past.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded moment after the start.</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, 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 should be included, or forced to <see langword="null"/>.</param>
|
||||
@@ -46,24 +47,22 @@ public class GetTagConsumptionQueryFixture
|
||||
public GetTagConsumptionQuery Create(
|
||||
string? targetUserId = null,
|
||||
string? libraryId = null,
|
||||
MediaKind? mediaKind = null,
|
||||
DateTime? fromUtc = null,
|
||||
DateTime? toUtc = 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)
|
||||
{
|
||||
DateTime resolvedFromUtc = fromUtc ?? (toUtc.HasValue
|
||||
? toUtc.Value.AddDays(-_faker.Random.Int(1, 30))
|
||||
: DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)));
|
||||
DateTime resolvedToUtc = toUtc ?? resolvedFromUtc.AddDays(_faker.Random.Int(1, 30));
|
||||
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 GetTagConsumptionQuery(
|
||||
includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds) : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null);
|
||||
}
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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="ClearResumePointsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="ClearResumePointsRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the deletion to. Defaults to a random Id.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="ClearResumePointsRequest"/>.</returns>
|
||||
public ClearResumePointsRequest Create(
|
||||
string? libraryId = null,
|
||||
bool includeLibraryId = true)
|
||||
{
|
||||
return new ClearResumePointsRequest(
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <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())];
|
||||
}
|
||||
}
|
||||
+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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAllUsersConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsRequestFixture
|
||||
{
|
||||
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="GetAllUsersConsumptionStatisticsRequest"/>.
|
||||
/// </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, 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="GetAllUsersConsumptionStatisticsRequest"/>.</returns>
|
||||
public GetAllUsersConsumptionStatisticsRequest 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 GetAllUsersConsumptionStatisticsRequest(
|
||||
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="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())];
|
||||
}
|
||||
}
|
||||
+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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsRequestFixture
|
||||
{
|
||||
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="GetConsumptionStatisticsRequest"/>.
|
||||
/// </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, 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="GetConsumptionStatisticsRequest"/>.</returns>
|
||||
public GetConsumptionStatisticsRequest 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 GetConsumptionStatisticsRequest(
|
||||
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="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())];
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMostConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedRequestFixture
|
||||
{
|
||||
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="GetMostConsumedRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the history to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="currentPage">Optional. The one based page of media items to return. Defaults to a bounded positive page.</param>
|
||||
/// <param name="perPage">Optional. The number of media items per page. Defaults to a bounded positive count.</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, 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="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the count per page 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="GetMostConsumedRequest"/>.</returns>
|
||||
public GetMostConsumedRequest Create(
|
||||
string? libraryId = null,
|
||||
string? mediaKind = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? fromUtc = null,
|
||||
string? toUtc = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeMediaKind = true,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = 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 GetMostConsumedRequest(
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeCurrentPage ? currentPage ?? _faker.Random.Int(1, 100) : null,
|
||||
includePerPage ? perPage ?? _faker.Random.Int(1, 50) : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <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())];
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetRecentlyConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedRequestFixture
|
||||
{
|
||||
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="GetRecentlyConsumedRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the history to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="currentPage">Optional. The one based page of media items to return. Defaults to a bounded positive page.</param>
|
||||
/// <param name="perPage">Optional. The number of media items per page. Defaults to a bounded positive count.</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, 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="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the count per page 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="GetRecentlyConsumedRequest"/>.</returns>
|
||||
public GetRecentlyConsumedRequest Create(
|
||||
string? libraryId = null,
|
||||
string? mediaKind = null,
|
||||
int? currentPage = null,
|
||||
int? perPage = null,
|
||||
string? fromUtc = null,
|
||||
string? toUtc = null,
|
||||
bool includeLibraryId = true,
|
||||
bool includeMediaKind = true,
|
||||
bool includeCurrentPage = true,
|
||||
bool includePerPage = 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 GetRecentlyConsumedRequest(
|
||||
includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
|
||||
includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
|
||||
includeCurrentPage ? currentPage ?? _faker.Random.Int(1, 100) : null,
|
||||
includePerPage ? perPage ?? _faker.Random.Int(1, 50) : null,
|
||||
includeFromUtc ? resolvedFromUtc : null,
|
||||
includeToUtc ? resolvedToUtc : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <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())];
|
||||
}
|
||||
}
|
||||
+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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetTagConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionRequestFixture
|
||||
{
|
||||
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="GetTagConsumptionRequest"/>.
|
||||
/// </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, 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="GetTagConsumptionRequest"/>.</returns>
|
||||
public GetTagConsumptionRequest 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 GetTagConsumptionRequest(
|
||||
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="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())];
|
||||
}
|
||||
}
|
||||
+357
@@ -0,0 +1,357 @@
|
||||
#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.ClearConsumptionHistory;
|
||||
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.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 5, 8, 20, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 5, 9, 5, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserHasHistory_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(15));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalled_ShouldPreserveTheCurrentUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(firstResumePointId, secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserHasNoHistory_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history";
|
||||
|
||||
// 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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 AssertConsumptionRecordsAreDeletedAsync(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 AssertConsumptionRecordsArePreservedAsync(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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.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 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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
#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.ClearConsumptionHistory;
|
||||
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.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 6, 12, 10, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 6, 12, 55, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenCurrentUserNamesThemselves_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{userId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenAdminNamesAnotherUser_ShouldDeleteEveryRecordOfThatUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history";
|
||||
|
||||
// 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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 AssertConsumptionRecordsAreDeletedAsync(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 AssertConsumptionRecordsArePreservedAsync(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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
#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.ClearResumePoints;
|
||||
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.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 7, 21, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 7, 21, 35, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyTheCurrentUsersResumePointsInThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsOmitted_ShouldDeleteEveryResumePointOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/media-resume-points");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/media-resume-points";
|
||||
|
||||
// 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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <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 AssertConsumptionRecordsArePreservedAsync(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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
#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.ClearResumePoints;
|
||||
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.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 8, 10, 30, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 8, 11, 10, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenCurrentUserNamesThemselves_ShouldDeleteEveryResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyThatLibrarysResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, firstLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{otherUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId, Guid.NewGuid());
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(targetResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/media-resume-points";
|
||||
|
||||
// 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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <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 AssertConsumptionRecordsArePreservedAsync(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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
#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.DeleteConsumptionRecord;
|
||||
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.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionRecordEndpointTests : 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,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordBelongsToCurrentUser_ShouldDeleteOnlyThatRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(10));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordDoesNotExist_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(existingRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/me/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenCalled_ShouldPreserveTheUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/consumption-history/{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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 AssertConsumptionRecordsAreDeletedAsync(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 AssertConsumptionRecordsArePreservedAsync(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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
#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.DeleteConsumptionRecord;
|
||||
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.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteUserConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionRecordEndpointTests : 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,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenCurrentUserNamesThemselves_ShouldDeleteTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(targetRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/not-a-guid/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{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="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <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 consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 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();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 AssertConsumptionRecordsAreDeletedAsync(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 AssertConsumptionRecordsArePreservedAsync(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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
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.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.GetAllUsersConsumptionStatistics;
|
||||
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.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_musicStartedOnUtc = new(2026, 3, 10, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 10, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated admin API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdmin_ShouldReturnPerUserSummariesAndCombinedTotals()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, Guid secondUserLibraryId) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
|
||||
ConsumptionSummaryResponse firstUser = Assert.Single(statistics!.Users, summary => summary.UserId == firstUserId);
|
||||
Assert.Equal(100d, firstUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, firstUser.CountedSessionCount);
|
||||
Assert.Equal(1, firstUser.CompletedSessionCount);
|
||||
Assert.Equal(1, firstUser.StoppedSessionCount);
|
||||
Assert.Equal(0.5, firstUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse firstUserMusic = Assert.Single(firstUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, firstUserMusic.MediaKind);
|
||||
Assert.Equal(100d, firstUserMusic.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
ConsumptionSummaryResponse secondUser = Assert.Single(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
Assert.Equal(400d, secondUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, secondUser.CountedSessionCount);
|
||||
Assert.Equal(1, secondUser.CompletedSessionCount);
|
||||
Assert.Equal(0, secondUser.StoppedSessionCount);
|
||||
Assert.Equal(1d, secondUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse secondUserBook = Assert.Single(secondUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, secondUserBook.MediaKind);
|
||||
Assert.Equal(400d, secondUserBook.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
Assert.Equal(statistics.Users.Select(summary => summary.UserId).Order().ToArray(), statistics.Users.Select(summary => summary.UserId).ToArray());
|
||||
Assert.NotEqual(firstUserLibraryId, secondUserLibraryId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByRegularUser_ShouldReturnForbiddenWithExactShape()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient regularClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await regularClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("users"));
|
||||
Assert.False(problemDetails.ContainsKey("total"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyTheUsersOfThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?libraryId={firstUserLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
ConsumptionSummaryResponse user = Assert.Single(statistics!.Users);
|
||||
Assert.Equal(firstUserId, user.UserId);
|
||||
Assert.Equal(100d, user.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(100d, statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse totalMusic = Assert.Single(statistics.Total.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, totalMusic.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.NotEmpty(statistics!.Users);
|
||||
Assert.All(statistics.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToStartDate_ShouldExcludeEarlierSessions()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every book record of this class starts in February, so a March start date can only leave music sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToEndDate_ShouldExcludeLaterSessions()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, _) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every music record of this class starts in March, so a February end date can only leave book sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == firstUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenTargetUserIdQueryParameterIsNotAValidGuid_ShouldIgnoreIt()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/consumption-statistics?userId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
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 GetAllUsersConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
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 GetAllUsersConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
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>
|
||||
/// Asserts that the combined totals are exactly the sum of the returned user summaries.
|
||||
/// </summary>
|
||||
/// <param name="statistics">The all users statistics response to assert on.</param>
|
||||
private static void AssertTotalsMatchUsers(AllUsersConsumptionStatisticsResponse statistics)
|
||||
{
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.TotalConsumedDurationInSeconds), statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CountedSessionCount), statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CompletedSessionCount), statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.StoppedSessionCount), statistics.Total.StoppedSessionCount);
|
||||
double expectedCompletionRate = statistics.Total.CountedSessionCount == 0
|
||||
? 0
|
||||
: (double)statistics.Total.CompletedSessionCount / statistics.Total.CountedSessionCount;
|
||||
Assert.Equal(expectedCompletionRate, statistics.Total.CompletionRate, 6);
|
||||
|
||||
MediaKind[] expectedMediaKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Select(summary => summary.MediaKind)
|
||||
.Distinct()
|
||||
.Order()];
|
||||
Assert.Equal(expectedMediaKinds, statistics.Total.MediaKindSummaries.Select(summary => summary.MediaKind).ToArray());
|
||||
foreach (MediaKindConsumptionSummaryResponse totalKind in statistics.Total.MediaKindSummaries)
|
||||
{
|
||||
List<MediaKindConsumptionSummaryResponse> userKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Where(summary => summary.MediaKind == totalKind.MediaKind)];
|
||||
Assert.Equal(userKinds.Sum(summary => summary.TotalConsumedDurationInSeconds), totalKind.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CountedSessionCount), totalKind.CountedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CompletedSessionCount), totalKind.CompletedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.StoppedSessionCount), totalKind.StoppedSessionCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with a music library and two counted music sessions.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its music library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedMusicOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"musicuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_musicStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_musicStartedOnUtc.AddMinutes(5), 40_000, 0);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with an ebook library and one counted book session and one uncounted one.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its ebook library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedBookOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"bookuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStartedOnUtc.AddMinutes(5), 100_000, 1);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type 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="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>
|
||||
/// 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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The authorization rows are removed with the users, so that the next test of the class can create its own admin user without colliding with the
|
||||
/// admin role permissions of the previous one.
|
||||
/// </remarks>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.MediaConsumptionRecords.ExecuteDeleteAsync();
|
||||
await dbContext.Libraries.ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+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.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.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedCountedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedUncountedStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackInProgressStartedOnUtc = new(2026, 3, 4, 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_bookStoppedFivePagesStartedOnUtc = new(2026, 2, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStoppedSixPagesStartedOnUtc = new(2026, 2, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookInProgressStartedOnUtc = new(2026, 2, 4, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenHistoryExists_ShouldApplyCountingRulesAndBreakdownByMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(359.999, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(4, summary.CountedSessionCount);
|
||||
Assert.Equal(2, summary.CompletedSessionCount);
|
||||
Assert.Equal(2, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
|
||||
Assert.Equal(2, summary.MediaKindSummaries.Count);
|
||||
|
||||
MediaKindConsumptionSummaryResponse trackSummary = summary.MediaKindSummaries[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(79.999, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, trackSummary.CountedSessionCount);
|
||||
Assert.Equal(1, trackSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, trackSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, trackSummary.CompletionRate, 6);
|
||||
|
||||
MediaKindConsumptionSummaryResponse bookSummary = summary.MediaKindSummaries[1];
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
Assert.Equal(280d, bookSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, bookSummary.CountedSessionCount);
|
||||
Assert.Equal(1, bookSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, bookSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, bookSummary.CompletionRate, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenStartDateCarriesAZoneDesignator_ShouldUseTheDescribedUtcInstant()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenHistoryIsEmpty_ShouldReturnZeroedTotalsAndEmptyBreakdown()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(0d, summary.TotalConsumedDurationInSeconds);
|
||||
Assert.Equal(0, summary.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(0d, summary.CompletionRate);
|
||||
Assert.Empty(summary.MediaKindSummaries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenInProgressSessionReachedTheThreshold_ShouldCountItTowardsStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
// The media kind rule counts a session when it completed or when it reached the threshold of its kind, which an in-progress session can do.
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackCompletedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(1, summary!.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(30d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(1, trackSummary.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
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 GetConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
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 GetConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
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");
|
||||
}
|
||||
|
||||
[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 async Task GetConsumptionStatistics_WhenADateBoundIsNotAValidDate_ShouldReturnValidationProblem(string invalidDate)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?fromUtc={Uri.EscapeDataString(invalidDate)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library and an ebook library owned by <paramref name="userId"/>, with one track and one book history.
|
||||
/// </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.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedCountedStartedOnUtc, 30_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedUncountedStartedOnUtc, 29_999, 0);
|
||||
// An in-progress session counts only through the threshold branch of its media kind rule, so it is kept below both thresholds here.
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackInProgressStartedOnUtc, 10_000, 0);
|
||||
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedFivePagesStartedOnUtc, 60_000, 5);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedSixPagesStartedOnUtc, 90_000, 6);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.InProgress, s_bookInProgressStartedOnUtc, 30_000, 2);
|
||||
|
||||
return (musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type 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="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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
#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.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.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_completedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_stoppedStartedOnUtc = new(2026, 3, 2, 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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_stoppedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(90d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(90d, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("mediaKindSummaries"));
|
||||
Assert.False(problemDetails.ContainsKey("countedSessionCount"));
|
||||
Assert.False(problemDetails.ContainsKey("totalConsumedDurationInSeconds"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenAdminNamesAnotherUser_ShouldReturnThatUsersStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(targetUserId, summary!.UserId);
|
||||
Assert.Equal(300d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(1d, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
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 type 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="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>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
#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.Entities.UsersManagement;
|
||||
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.MediaContributors;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackAFirstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackASecondStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackAThirdStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBFirstStartedOnUtc = new(2026, 3, 2, 8, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBSecondStartedOnUtc = new(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookFirstStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookSecondStartedOnUtc = new(2026, 2, 2, 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 BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenHistoryExists_ShouldOrderByCountedSessionsThenDurationThenLastConsumed()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(3, history.Data.Count);
|
||||
|
||||
Assert.Equal(new[] { trackAId, trackBId, bookCId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
|
||||
ConsumedItemResponse mostConsumed = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, mostConsumed.MediaKind);
|
||||
Assert.Equal(musicLibraryId, mostConsumed.LibraryId);
|
||||
Assert.True(mostConsumed.IsAvailable);
|
||||
Assert.Equal("Track A", mostConsumed.Title);
|
||||
Assert.Equal("Album A", mostConsumed.CollectionTitle);
|
||||
Assert.Equal("Artist A", mostConsumed.CreatorName);
|
||||
Assert.Null(mostConsumed.CoverPath);
|
||||
Assert.Equal(s_trackAThirdStartedOnUtc, mostConsumed.LastConsumedOnUtc);
|
||||
Assert.Equal(3, mostConsumed.CountedSessionCount);
|
||||
Assert.Equal(3, mostConsumed.CompletedSessionCount);
|
||||
Assert.Equal(30d, mostConsumed.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse second = history.Data[1];
|
||||
Assert.Equal(trackBId, second.MediaItemId);
|
||||
Assert.Equal(2, second.CountedSessionCount);
|
||||
Assert.Equal(200d, second.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBSecondStartedOnUtc, second.LastConsumedOnUtc);
|
||||
|
||||
ConsumedItemResponse third = history.Data[2];
|
||||
Assert.Equal(bookCId, third.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, third.LibraryId);
|
||||
Assert.Equal(2, third.CountedSessionCount);
|
||||
Assert.Equal(200d, third.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_bookSecondStartedOnUtc, third.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.All(history!.Data, item => Assert.Equal(MediaKind.MusicTrack, item.MediaKind));
|
||||
Assert.Equal(new[] { trackAId, trackBId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-02T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(new[] { trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(2, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(20d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T08:30:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the February book sessions and drops the later track sessions, which changes both the counts and the order.
|
||||
Assert.Equal(new[] { bookCId, trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(100d, history.Data[1].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBFirstStartedOnUtc, history.Data[1].LastConsumedOnUtc);
|
||||
Assert.Equal(1, history.Data[2].CountedSessionCount);
|
||||
Assert.Equal(10d, history.Data[2].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackAFirstStartedOnUtc, history.Data[2].LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
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 GetMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetMostConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
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 GetMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
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 two tracks with three and two sessions and a book with two sessions, all owned by <paramref name="userId"/>.
|
||||
/// </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, both tracks, the ebook library, and the book.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackAId = await SeedTrackAsync(musicLibraryId, "Track A", "Album A", "Artist A");
|
||||
Guid trackBId = await SeedTrackAsync(musicLibraryId, "Track B", "Album B", "Artist B");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
Guid bookCId = await SeedBookAsync(bookLibraryId, "Book C", $"Author C {Guid.NewGuid():N}");
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAFirstStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackASecondStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAThirdStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBFirstStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBSecondStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookFirstStartedOnUtc, 100_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookSecondStartedOnUtc, 100_000, 10);
|
||||
|
||||
return (musicLibraryId, trackAId, trackBId, bookLibraryId, bookCId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type 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 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>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
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);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </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="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
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="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,
|
||||
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: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
#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.Entities.UsersManagement;
|
||||
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.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_firstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_secondStartedOnUtc = new(2026, 3, 2, 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 BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid mostConsumedBookId = await SeedBookAsync(libraryId, "Most Consumed Book", "Author One");
|
||||
Guid lessConsumedBookId = await SeedBookAsync(libraryId, "Less Consumed Book", "Author Two");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_secondStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, lessConsumedBookId, s_secondStartedOnUtc, 300_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.Count);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(new[] { mostConsumedBookId, lessConsumedBookId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(240d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal("Most Consumed Book", history.Data[0].Title);
|
||||
Assert.Equal("Author One", history.Data[0].CreatorName);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, s_firstStartedOnUtc, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/most-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
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 type 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 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>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
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);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </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="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
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="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,
|
||||
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: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
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>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
#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.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.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackFirstStartedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackFirstLastActivityOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondStartedOnUtc = new(2026, 3, 2, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondLastActivityOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdStartedOnUtc = new(2026, 3, 3, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdLastActivityOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 28, 19, 50, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookLastActivityOnUtc = new(2026, 2, 28, 20, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_missingItemLastActivityOnUtc = new(2026, 3, 5, 12, 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 BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenCalledForCurrentUser_ShouldReturnAggregatedHistory()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(2, history.Data.Count);
|
||||
|
||||
ConsumedItemResponse track = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, track.MediaKind);
|
||||
Assert.Equal(trackId, track.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, track.LibraryId);
|
||||
Assert.True(track.IsAvailable);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
Assert.Equal("A Night at the Opera", track.CollectionTitle);
|
||||
Assert.Equal("Queen", track.CreatorName);
|
||||
Assert.Null(track.CoverPath);
|
||||
Assert.Equal(s_trackThirdLastActivityOnUtc, track.LastConsumedOnUtc);
|
||||
Assert.Equal(2, track.CountedSessionCount);
|
||||
Assert.Equal(1, track.CompletedSessionCount);
|
||||
Assert.Equal(100d, track.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse book = history.Data[1];
|
||||
Assert.Equal(MediaKind.Book, book.MediaKind);
|
||||
Assert.Equal(bookId, book.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, book.LibraryId);
|
||||
Assert.True(book.IsAvailable);
|
||||
Assert.Equal("The Fellowship of the Ring", book.Title);
|
||||
Assert.Equal(string.Empty, book.CollectionTitle);
|
||||
Assert.Equal(authorName, book.CreatorName);
|
||||
Assert.Null(book.CoverPath);
|
||||
Assert.Equal(s_bookLastActivityOnUtc, book.LastConsumedOnUtc);
|
||||
Assert.Equal(1, book.CountedSessionCount);
|
||||
Assert.Equal(1, book.CompletedSessionCount);
|
||||
Assert.Equal(500d, book.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid bookLibraryId, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(2, item.CountedSessionCount);
|
||||
Assert.Equal(100d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the book session of February and drops only the third track session of March, which started after it.
|
||||
Assert.Equal(new[] { trackId, bookId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(1, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(1, history.Data[0].CompletedSessionCount);
|
||||
Assert.Equal(55d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackSecondLastActivityOnUtc, history.Data[0].LastConsumedOnUtc);
|
||||
Assert.Equal(500d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid newestBookId = await SeedBookAsync(libraryId, "Newest Book");
|
||||
Guid middleBookId = await SeedBookAsync(libraryId, "Middle Book");
|
||||
Guid oldestBookId = await SeedBookAsync(libraryId, "Oldest Book");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, newestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 3, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, middleBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, oldestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(oldestBookId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenAnotherUserHasHistory_ShouldReturnOnlyCurrentUserItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Own Library");
|
||||
Guid ownBookId = await SeedBookAsync(ownLibraryId, "Own Book");
|
||||
await SeedRecordAsync(userId, ownLibraryId, MediaKind.Book, ownBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(ownBookId, item.MediaItemId);
|
||||
Assert.Equal("Own Book", item.Title);
|
||||
Assert.DoesNotContain(history.Data, candidate => candidate.Title == "Other User Secret Book");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenMediaItemNoLongerExists_ShouldReturnCountsWithBlankDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid missingTrackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, missingTrackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_missingItemLastActivityOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(missingTrackId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
Assert.Equal(string.Empty, item.CollectionTitle);
|
||||
Assert.Equal(string.Empty, item.CreatorName);
|
||||
Assert.Null(item.CoverPath);
|
||||
Assert.Equal(s_missingItemLastActivityOnUtc, item.LastConsumedOnUtc);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
Assert.Equal(1, item.CompletedSessionCount);
|
||||
Assert.Equal(30d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
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 GetRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetRecentlyConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
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 GetRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
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 two libraries owned by <paramref name="userId"/>, a track with three sessions, and a book with one session.
|
||||
/// </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, the track, the ebook library, and the book, and the unique name of the book author.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
string authorName = $"J. R. R. Tolkien {Guid.NewGuid():N}";
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", []);
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", authorName, []);
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_trackFirstLastActivityOnUtc, 40_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackSecondStartedOnUtc, s_trackSecondLastActivityOnUtc, 15_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackThirdStartedOnUtc, s_trackThirdLastActivityOnUtc, 45_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, s_bookLastActivityOnUtc, 500_000, 10);
|
||||
|
||||
return (musicLibraryId, trackId, bookLibraryId, bookId, authorName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type 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 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="tagNames">The tag 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> tagNames)
|
||||
{
|
||||
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 tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </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="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <param name="tagNames">The tag names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null, IReadOnlyList<string>? tagNames = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames ?? [])
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <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="lastActivityOnUtc">The date and time when the session last received activity.</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,
|
||||
DateTime lastActivityOnUtc,
|
||||
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: lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : lastActivityOnUtc.AddMinutes(1),
|
||||
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>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
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 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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
#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.Entities.UsersManagement;
|
||||
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.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = 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 BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnSameDataAsMeRoute()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(libraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string query = "currentPage=1&perPage=10";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage meResponse = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?{query}");
|
||||
HttpResponseMessage userResponse = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?{query}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, meResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, userResponse.StatusCode);
|
||||
AssertCacheHeaders(userResponse);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? meHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(meResponse);
|
||||
PaginatedResponse<ConsumedItemResponse>? userHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(userResponse);
|
||||
Assert.NotNull(meHistory);
|
||||
Assert.NotNull(userHistory);
|
||||
Assert.Equal(meHistory!.Count, userHistory!.Count);
|
||||
Assert.Equal(meHistory.CurrentPage, userHistory.CurrentPage);
|
||||
Assert.Equal(meHistory.PerPage, userHistory.PerPage);
|
||||
Assert.Equal(meHistory.NumberOfPages, userHistory.NumberOfPages);
|
||||
Assert.Equal(JsonSerializer.Serialize(meHistory.Data, _jsonOptions), JsonSerializer.Serialize(userHistory.Data, _jsonOptions));
|
||||
|
||||
ConsumedItemResponse item = Assert.Single(userHistory.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", item.Title);
|
||||
Assert.Equal("J. R. R. Tolkien", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserHasNoHistory_ShouldReturnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?currentPage=1&perPage=50");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Empty(history!.Data);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(50, history.PerPage);
|
||||
Assert.Equal(0, history.Count);
|
||||
Assert.Equal(0, history.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersData()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, ConsumptionStatus.Completed, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal("Innuendo", item.CollectionTitle);
|
||||
Assert.Equal("Queen", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
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 type 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 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>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
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);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </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="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
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="status">The state of the session.</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,
|
||||
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: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : s_lastActivityOnUtc.AddMinutes(1),
|
||||
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>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
#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.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : 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 TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenTaggedItemsWereConsumed_ShouldReturnLowercaseTagsOrderedByItemCountThenDurationThenName()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(3, tags!.Count);
|
||||
Assert.All(tags, tag => Assert.Equal(tag.Name.ToLowerInvariant(), tag.Name));
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), bookClubTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
|
||||
Assert.Equal(2, tags[0].ConsumedItemCount);
|
||||
Assert.Equal(370d, tags[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[1].ConsumedItemCount);
|
||||
Assert.Equal(300d, tags[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[2].ConsumedItemCount);
|
||||
Assert.Equal(70d, tags[2].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
Assert.NotEqual(musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId, string favouriteTag, string bookClubTag, _, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, string bookClubTag, _, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Empty(tags!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
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 GetTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetTagConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
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 GetTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
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 tagged track with a counted and an uncounted session, a tagged book with a counted session, and a tagged book without any counted session.
|
||||
/// </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 favourite, book club, rock, and ignored tag names that were seeded.
|
||||
/// </returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag)> SeedTaggedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// Each test seeds its own tag rows, so every name carries a unique suffix to keep the shared Tags table collision free.
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
string favouriteTag = $"Favourite-{suffix}";
|
||||
string bookClubTag = $"Book-Club-{suffix}";
|
||||
string rockTag = $"Rock-{suffix}";
|
||||
string ignoredTag = $"Ignored-{suffix}";
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// The track and the book share a tag, so the tag rows are resolved once per name, and the whole graph is saved through one context, so the
|
||||
// shared row is inserted once instead of once per item that carries it.
|
||||
Dictionary<string, TagEntity> tags = [];
|
||||
TagEntity ResolveTag(string name)
|
||||
{
|
||||
if (!tags.TryGetValue(name, out TagEntity? tag))
|
||||
{
|
||||
tag = _tagEntityFixture.Create(name: name);
|
||||
tags[name] = tag;
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
Guid musicLibraryId = Guid.NewGuid();
|
||||
Guid bookLibraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = 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 track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
|
||||
track.Tags.Add(ResolveTag(rockTag));
|
||||
track.Tags.Add(ResolveTag(favouriteTag));
|
||||
dbContext.Tracks.Add(track);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
|
||||
book.Tags.Add(ResolveTag(favouriteTag));
|
||||
book.Tags.Add(ResolveTag(bookClubTag));
|
||||
dbContext.Books.Add(book);
|
||||
|
||||
BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
|
||||
uncountedBook.Tags.Add(ResolveTag(ignoredTag));
|
||||
dbContext.Books.Add(uncountedBook);
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 10_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, favouriteTag, bookClubTag, rockTag, ignoredTag);
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
#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.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.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
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.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserTagConsumptionEndpointTests : 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 TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
string firstTag = $"First-{Guid.NewGuid():N}";
|
||||
string secondTag = $"Second-{Guid.NewGuid():N}";
|
||||
Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstTag, secondTag]);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(2, tags!.Count);
|
||||
Assert.Equal(
|
||||
new[] { firstTag.ToLowerInvariant(), secondTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(60d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
string secretTag = $"Secret-{Guid.NewGuid():N}";
|
||||
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretTag]);
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(secretTag.ToLowerInvariant(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
string targetTag = $"Target-{Guid.NewGuid():N}";
|
||||
Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetTag]);
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(targetTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.Equal(1, tag.ConsumedItemCount);
|
||||
Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
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 type 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 tagged 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="tagNames">The tag 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> tagNames)
|
||||
{
|
||||
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 tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged 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="tagNames">The tag 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> tagNames)
|
||||
{
|
||||
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 tagName in tagNames)
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
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>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
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>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
#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.ClearConsumptionHistory;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : 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-history";
|
||||
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 5, 3, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 3, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(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 ClearConsumptionHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(PATH);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalled_ShouldDeleteOnlyTheCallersHistoryAndPreserveResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
Guid ownOtherRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
Guid ownResumePointId = await SeedResumePointAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
await AssertRecordsAreDeletedAsync(ownRecordId, ownOtherRecordId);
|
||||
await AssertRecordsArePreservedAsync(otherUserRecordId);
|
||||
// Clearing the history is a separate user action from clearing the continue watching list, so resume points survive.
|
||||
await AssertResumePointsArePreservedAsync(ownResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndClearOnlyTheCallersHistory()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string url = $"{PATH}?userId={otherUserId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
// The me route always targets the authenticated caller, so a spoofed query parameter cannot redirect the deletion.
|
||||
await AssertRecordsAreDeletedAsync(ownRecordId);
|
||||
await AssertRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WithInjectionInSpoofedUserIdQueryParameter_ShouldIgnoreItAndRemainSecure()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string maliciousUserId = "'; DROP TABLE MediaConsumptionRecords--";
|
||||
string url = $"{PATH}?userId={Uri.EscapeDataString(maliciousUserId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
|
||||
|
||||
// The unused query parameter never reaches the query builder, so the caller's own rows are deleted and the other user's rows survive.
|
||||
await AssertRecordsAreDeletedAsync(ownRecordId);
|
||||
await AssertRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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 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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary 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);
|
||||
}
|
||||
}
|
||||
+505
@@ -0,0 +1,505 @@
|
||||
#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.ClearConsumptionHistory;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserConsumptionHistoryEndpointTests : 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";
|
||||
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 5, 4, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 4, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = 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="ClearUserConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserConsumptionHistoryEndpointTests(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 ClearUserConsumptionHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenCallerNamesThemselves_ShouldClearTheOwnHistory()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
|
||||
|
||||
// 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 ClearUserConsumptionHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheHistory()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
|
||||
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
|
||||
|
||||
// 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 ClearUserConsumptionHistory_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
|
||||
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
|
||||
|
||||
// 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 ClearUserConsumptionHistory_WhenAdminNamesAnotherUser_ShouldClearThatUsersHistory()
|
||||
{
|
||||
// Arrange
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
|
||||
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
|
||||
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);
|
||||
await AssertResumePointsArePreservedAsync(targetResumePointId);
|
||||
}
|
||||
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 ClearUserConsumptionHistory_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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()));
|
||||
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 or reaching the data access layer.
|
||||
/// </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();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, 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"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary 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();
|
||||
}
|
||||
}
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
#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.ClearResumePoints;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : 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/media-resume-points";
|
||||
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 5, 5, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 5, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearResumePointsEndpointTests(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 ClearResumePoints_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(PATH);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, PATH);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsOmitted_ShouldDeleteOnlyTheCallersResumePointsAndPreserveHistory()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First Owner Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second Owner Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId);
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId);
|
||||
Guid recordId = await SeedRecordAsync(userId, firstLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(PATH);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
// Removing the resume points does not touch the history, so the consumption records survive.
|
||||
await AssertRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WithLibraryId_ShouldDeleteOnlyTheCallersResumePointsInThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid targetLibraryId = await SeedLibraryAsync(userId, "Target Owner Library");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(userId, "Other Owner Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(userId, targetLibraryId);
|
||||
Guid otherResumePointId = await SeedResumePointAsync(userId, otherLibraryId);
|
||||
Guid recordId = await SeedRecordAsync(userId, targetLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
|
||||
string url = $"{PATH}?libraryId={targetLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
|
||||
|
||||
await AssertResumePointsAreDeletedAsync(targetResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherResumePointId, otherUserResumePointId);
|
||||
await AssertRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndNeverDeleteTheOtherUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownResumePointId = await SeedResumePointAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
|
||||
string url = $"{PATH}?libraryId={otherUserLibraryId}&userId={otherUserId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
// The me route always targets the authenticated caller, so the spoofed user Id cannot turn the request into a deletion of the other user's rows.
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId, ownResumePointId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaResumePoints--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaResumePoints")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ClearResumePoints_WithInjectionInLibraryIdQueryParameter_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
|
||||
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedQueryInjectionAsync(response, maliciousLibraryId, PATH, "LibraryIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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 query value is rejected with the exact RFC 4918 validation problem shape.
|
||||
/// </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 on.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedQueryInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
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(requestPath, 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);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <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 per-user responses are not storable by any intermediary and vary 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);
|
||||
}
|
||||
}
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
#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.ClearResumePoints;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserResumePointsEndpointTests : 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 = "/media-resume-points";
|
||||
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 5, 6, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 6, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = 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="ClearUserResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserResumePointsEndpointTests(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 ClearUserResumePoints_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenCallerNamesThemselves_ShouldClearTheOwnResumePointsAndPreserveHistory()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
|
||||
await AssertResumePointsAreDeletedAsync(resumePointId);
|
||||
await AssertRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
|
||||
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertForbiddenAsync(response, url);
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
await AssertResumePointsArePreservedAsync(targetResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId);
|
||||
string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
|
||||
string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
|
||||
|
||||
// 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 AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenAdminNamesAnotherUser_ShouldClearOnlyThatUsersResumePointsInTheNamedLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid otherTargetLibraryId = await SeedLibraryAsync(targetUserId, "Other Target User Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
|
||||
Guid otherTargetResumePointId = await SeedResumePointAsync(targetUserId, otherTargetLibraryId);
|
||||
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
|
||||
string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}?libraryId={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 AssertResumePointsAreDeletedAsync(targetResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherTargetResumePointId);
|
||||
await AssertRecordsArePreservedAsync(targetRecordId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaResumePoints--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaResumePoints")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ClearUserResumePoints_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
|
||||
string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedRouteInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaResumePoints--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaResumePoints")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ClearUserResumePoints_WithInjectionInLibraryIdQueryParameter_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
|
||||
string path = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}";
|
||||
string url = $"{path}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedQueryInjectionAsync(response, maliciousLibraryId, path, "LibraryIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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()));
|
||||
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 or reaching the data access layer.
|
||||
/// </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 AssertRejectedRouteInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, 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"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious query value is rejected with the exact RFC 4918 validation problem shape.
|
||||
/// </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 on.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedQueryInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
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(requestPath, 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);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <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 per-user responses are not storable by any intermediary and vary 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();
|
||||
}
|
||||
}
|
||||
+440
@@ -0,0 +1,440 @@
|
||||
#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.DeleteConsumptionRecord;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionRecordEndpointTests : 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionRecordEndpointTests(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 DeleteConsumptionRecord_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenOwnRecordIsDeleted_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId);
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
await AssertRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenAnotherUsersRecordIdIsUsed_ShouldSucceedAndPreserveThatRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string url = $"/api/v1/users/me/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
|
||||
|
||||
// Deleting a record that does not belong to the caller succeeds, but it must never remove the other user's row.
|
||||
await AssertRecordsArePreservedAsync(otherUserRecordId);
|
||||
await AssertRecordsArePreservedAsync(ownRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndDeleteOnlyTheOwnRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string url = $"/api/v1/users/me/consumption-history/{ownRecordId}?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);
|
||||
}
|
||||
|
||||
[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 DeleteConsumptionRecord_WithInjectionInRecordId_ShouldRejectWithoutDeletingRows(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"/api/v1/users/me/consumption-history/{Uri.EscapeDataString(maliciousRecordId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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 without disclosing internals or reaching the data access layer.
|
||||
/// </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();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, 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"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary 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);
|
||||
}
|
||||
}
|
||||
+526
@@ -0,0 +1,526 @@
|
||||
#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.DeleteConsumptionRecord;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteUserConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionRecordEndpointTests : 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, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = 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="DeleteUserConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionRecordEndpointTests(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 DeleteUserConsumptionRecord_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenCallerNamesThemselves_ShouldDeleteTheOwnRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{recordId}";
|
||||
|
||||
// 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 DeleteUserConsumptionRecord_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
|
||||
|
||||
// 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 DeleteUserConsumptionRecord_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId);
|
||||
string foreignUrl = $"/api/v1/users/{otherUserId}/consumption-history/{otherUserRecordId}";
|
||||
string missingUrl = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{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 DeleteUserConsumptionRecord_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid targetUserId, _) = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId);
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId);
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
|
||||
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);
|
||||
await AssertResumePointsArePreservedAsync(targetResumePointId);
|
||||
}
|
||||
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 DeleteUserConsumptionRecord_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"/api/v1/users/{Uri.EscapeDataString(maliciousUserId)}/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
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 DeleteUserConsumptionRecord_WithInjectionInRecordIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Owner Library");
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{Uri.EscapeDataString(maliciousRecordId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertNonCacheable(response);
|
||||
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 music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns 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, 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.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track of <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 consumed track.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
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.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <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()));
|
||||
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 or reaching the data access layer.
|
||||
/// </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();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, 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"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
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 resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point 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++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary 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();
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
#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.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.GetAllUsersConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : 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/consumption-statistics";
|
||||
|
||||
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 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="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(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 GetAllUsersConsumptionStatistics_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByRegularUser_ShouldReturnForbiddenWithoutAnyUserStatistics()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(otherUserId);
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertForbiddenAsync(response, url);
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(otherUsername, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("\"users\"", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("\"total\"", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdmin_ShouldReturnEveryUsersStatisticsWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(userId);
|
||||
HttpClient adminClient = _apiFactory.CreateClient();
|
||||
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
|
||||
_adminUserIds.Add(adminUserId);
|
||||
string url = PATH;
|
||||
|
||||
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);
|
||||
|
||||
AllUsersConsumptionStatisticsResponse? statistics = JsonSerializer.Deserialize<AllUsersConsumptionStatisticsResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(statistics);
|
||||
// The only records of this test belong to the seeded user, so no other account may appear in the admin summary.
|
||||
ConsumptionSummaryResponse summary = Assert.Single(statistics!.Users);
|
||||
Assert.Equal(userId, summary.UserId);
|
||||
Assert.Equal(60d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, summary.CountedSessionCount);
|
||||
Assert.Equal(60d, statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, statistics.Total.CountedSessionCount);
|
||||
Assert.DoesNotContain(adminUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
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 GetAllUsersConsumptionStatistics_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(userId);
|
||||
HttpClient adminClient = _apiFactory.CreateClient();
|
||||
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
|
||||
_adminUserIds.Add(adminUserId);
|
||||
string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.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 == userId));
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // out of range numeric value
|
||||
[InlineData("not-a-media-kind")] // textual value that is not an enum member
|
||||
public async Task GetAllUsersConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(userId);
|
||||
HttpClient adminClient = _apiFactory.CreateClient();
|
||||
Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
|
||||
_adminUserIds.Add(adminUserId);
|
||||
string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.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);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the records.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
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 libraryId;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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("\"users\"", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("\"total\"", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <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 statistics 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)
|
||||
{
|
||||
// The user Id is a documented statistics field, so it is not asserted absent here.
|
||||
Assert.DoesNotContain("version", 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();
|
||||
}
|
||||
}
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
#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.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.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : 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";
|
||||
|
||||
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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(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 GetConsumptionStatistics_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenSuccessful_ShouldReturnOnlyCallersStatisticsWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(callerId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(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(otherUserId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(statistics);
|
||||
// The user Id is part of the documented statistics contract, so it must be present and must be the callers.
|
||||
Assert.Equal(callerId, statistics!.UserId);
|
||||
Assert.Equal(60d, statistics.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, statistics.CountedSessionCount);
|
||||
Assert.Equal(1, statistics.CompletedSessionCount);
|
||||
Assert.Equal(0, statistics.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse kind = Assert.Single(statistics.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, kind.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersStatistics()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(callerId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(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();
|
||||
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.Equal(callerId, statistics!.UserId);
|
||||
Assert.DoesNotContain(otherUserId.ToString(), 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 GetConsumptionStatistics_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(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("' 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 GetConsumptionStatistics_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(callerId);
|
||||
string url = $"{PATH}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, PATH, "ConsumptionDateRangeIsInvalid");
|
||||
AssertNonCacheable(response);
|
||||
Assert.DoesNotContain(maliciousFromUtc, 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 GetConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the records.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
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 libraryId;
|
||||
}
|
||||
|
||||
/// <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("\"mediaKindSummaries\"", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 statistics 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)
|
||||
{
|
||||
// The user Id is a documented statistics field, so it is not asserted absent here.
|
||||
Assert.DoesNotContain("version", 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);
|
||||
}
|
||||
}
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
#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.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.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserConsumptionStatisticsEndpointTests : 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";
|
||||
|
||||
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 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="GetUserConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserConsumptionStatisticsEndpointTests(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 GetUserConsumptionStatistics_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 GetUserConsumptionStatistics_WhenAnotherUsersStatisticsAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(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("countedSessionCount", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("totalConsumedDurationInSeconds", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(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 GetUserConsumptionStatistics_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersStatistics()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedCompletedMusicSessionAsync(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);
|
||||
|
||||
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.Equal(otherUserId, statistics!.UserId);
|
||||
Assert.Equal(60d, statistics.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, statistics.CountedSessionCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenCallerNamesThemselves_ShouldReturnOwnStatistics()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(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();
|
||||
ConsumptionSummaryResponse? statistics = JsonSerializer.Deserialize<ConsumptionSummaryResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.Equal(callerId, statistics!.UserId);
|
||||
}
|
||||
|
||||
[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 GetUserConsumptionStatistics_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(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("999")] // out of range numeric value
|
||||
[InlineData("not-a-media-kind")] // textual value that is not an enum member
|
||||
public async Task GetUserConsumptionStatistics_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedCompletedMusicSessionAsync(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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and one completed consumption session of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the records.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedCompletedMusicSessionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
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 libraryId;
|
||||
}
|
||||
|
||||
/// <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 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("\"mediaKindSummaries\"", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 statistics 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)
|
||||
{
|
||||
// The user Id is a documented statistics field, so it is not asserted absent here.
|
||||
Assert.DoesNotContain("version", 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();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
#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.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
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.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : 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-history/most-consumed";
|
||||
|
||||
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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetMostConsumedEndpointTests(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 GetMostConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenSuccessful_ShouldReturnOnlyCallersDataWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid callerLibraryId, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Most-Consumed");
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
|
||||
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(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Foreign-Most-Consumed", content, StringComparison.Ordinal);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
Assert.Equal(callerLibraryId, item.LibraryId);
|
||||
Assert.Equal("Caller-Most-Consumed", item.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Spoof-Target");
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Spoof-Target");
|
||||
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();
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
Assert.NotEqual(otherMediaItemId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[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 GetMostConsumed_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
|
||||
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(2, 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 GetMostConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and two completed consumption sessions of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the history.</param>
|
||||
/// <param name="title">The title of the consumed track.</param>
|
||||
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
|
||||
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
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));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
|
||||
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));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc.AddDays(1),
|
||||
lastActivityOnUtc: s_lastActivityOnUtc.AddDays(1),
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 60_000,
|
||||
lastProgressFraction: 1.0,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <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("\"data\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 consumed items 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);
|
||||
}
|
||||
}
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
#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.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
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.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserMostConsumedEndpointTests : 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/most-consumed";
|
||||
|
||||
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 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="GetUserMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserMostConsumedEndpointTests(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 GetUserMostConsumed_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 GetUserMostConsumed_WhenAnotherUsersHistoryIsRequested_ShouldReturnForbiddenWithoutDisclosingData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
|
||||
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(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Foreign-Most-Consumed", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedConsumedTrackAsync(otherUserId, "Foreign-Indistinguishable");
|
||||
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 GetUserMostConsumed_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Most-Consumed");
|
||||
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);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(otherMediaItemId, item.MediaItemId);
|
||||
Assert.Equal("Foreign-Most-Consumed", item.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenCallerNamesThemselves_ShouldReturnOwnData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Most-Consumed");
|
||||
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();
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[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 GetUserMostConsumed_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
|
||||
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(2, 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 GetUserMostConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and two completed consumption sessions of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the history.</param>
|
||||
/// <param name="title">The title of the consumed track.</param>
|
||||
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
|
||||
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
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));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
|
||||
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));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: Guid.NewGuid(),
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc.AddDays(1),
|
||||
lastActivityOnUtc: s_lastActivityOnUtc.AddDays(1),
|
||||
consumedDurationMilliseconds: 60_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 60_000,
|
||||
lastProgressFraction: 1.0,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <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 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("\"data\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 consumed items 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();
|
||||
}
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
#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.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
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.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : 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-history/recently-consumed";
|
||||
|
||||
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 MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(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 GetRecentlyConsumed_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenSuccessful_ShouldReturnOnlyCallersDataWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid callerLibraryId, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Recently-Consumed");
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
|
||||
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(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Foreign-Recently-Consumed", content, StringComparison.Ordinal);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
Assert.Equal(callerLibraryId, item.LibraryId);
|
||||
Assert.Equal("Caller-Recently-Consumed", item.Title);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Spoof-Target");
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Spoof-Target");
|
||||
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();
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
Assert.NotEqual(otherMediaItemId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[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 GetRecentlyConsumed_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
|
||||
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 GetRecentlyConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and a completed consumption session of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the history.</param>
|
||||
/// <param name="title">The title of the consumed track.</param>
|
||||
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
|
||||
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
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));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
|
||||
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 (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <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("\"data\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 consumed items 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);
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
#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.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
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.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRecentlyConsumedEndpointTests : 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/recently-consumed";
|
||||
|
||||
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 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="GetUserRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRecentlyConsumedEndpointTests(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 GetUserRecentlyConsumed_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 GetUserRecentlyConsumed_WhenAnotherUsersHistoryIsRequested_ShouldReturnForbiddenWithoutDisclosingData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
|
||||
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(otherMediaItemId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Foreign-Recently-Consumed", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedConsumedTrackAsync(otherUserId, "Foreign-Indistinguishable");
|
||||
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 GetUserRecentlyConsumed_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherMediaItemId) = await SeedConsumedTrackAsync(otherUserId, "Foreign-Recently-Consumed");
|
||||
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);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(otherMediaItemId, item.MediaItemId);
|
||||
Assert.Equal("Foreign-Recently-Consumed", item.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenCallerNamesThemselves_ShouldReturnOwnData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid callerMediaItemId) = await SeedConsumedTrackAsync(callerId, "Caller-Recently-Consumed");
|
||||
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();
|
||||
PaginatedResponse<ConsumedItemResponse>? history = JsonSerializer.Deserialize<PaginatedResponse<ConsumedItemResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(callerMediaItemId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[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 GetUserRecentlyConsumed_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Injection-Target");
|
||||
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("999")] // out of range numeric value
|
||||
[InlineData("not-a-media-kind")] // textual value that is not an enum member
|
||||
public async Task GetUserRecentlyConsumed_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedConsumedTrackAsync(callerId, "Caller-Media-Kind-Target");
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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 music library owned by <paramref name="userId"/> and a completed consumption session of one of its tracks.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the history.</param>
|
||||
/// <param name="title">The title of the consumed track.</param>
|
||||
/// <returns>The Ids of the seeded library and of the consumed media item.</returns>
|
||||
private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
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));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: title, includeMetadata: false));
|
||||
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 (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <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 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("\"data\"", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <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 consumed items 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();
|
||||
}
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
#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.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : 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/tags";
|
||||
|
||||
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 TagEntityFixture _tagEntityFixture = 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="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTagConsumptionEndpointTests(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 GetTagConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = PATH;
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenSuccessful_ShouldReturnOnlyCallersTagsWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
string callerTag = await SeedTaggedConsumptionAsync(callerId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
string otherTag = await SeedTaggedConsumptionAsync(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(otherTag, content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
List<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(callerTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.Equal(1, tag.ConsumedItemCount);
|
||||
Assert.Equal(60d, tag.ConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersTags()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
string callerTag = await SeedTaggedConsumptionAsync(callerId);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
string otherTag = await SeedTaggedConsumptionAsync(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<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(callerTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.DoesNotContain(otherTag, 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 GetTagConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedTaggedConsumptionAsync(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 GetTagConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedTaggedConsumptionAsync(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);
|
||||
}
|
||||
|
||||
/// <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 tagged 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 tag.</returns>
|
||||
private async Task<string> SeedTaggedConsumptionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
// Tag names are the primary key of a shared table, so every seeded name carries a unique suffix.
|
||||
string tagName = $"tag-{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);
|
||||
TagEntity tag = _tagEntityFixture.Create(name: tagName);
|
||||
track.Tags.Add(tag);
|
||||
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 tagName;
|
||||
}
|
||||
|
||||
/// <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 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 tags 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);
|
||||
}
|
||||
}
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
#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.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserTagConsumptionEndpointTests : 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/tags";
|
||||
|
||||
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 TagEntityFixture _tagEntityFixture = 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="GetUserTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserTagConsumptionEndpointTests(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 GetUserTagConsumption_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 GetUserTagConsumption_WhenAnotherUsersTagsAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
string otherTag = await SeedTaggedConsumptionAsync(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(otherTag, content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("consumedItemCount", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
await SeedTaggedConsumptionAsync(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 GetUserTagConsumption_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersTags()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
string otherTag = await SeedTaggedConsumptionAsync(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<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(otherTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.Equal(1, tag.ConsumedItemCount);
|
||||
}
|
||||
finally
|
||||
{
|
||||
adminClient.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenCallerNamesThemselves_ShouldReturnOwnTags()
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
string callerTag = await SeedTaggedConsumptionAsync(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<TagConsumptionResponse>? tags = JsonSerializer.Deserialize<List<TagConsumptionResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(callerTag.ToLowerInvariant(), tag.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 GetUserTagConsumption_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedTaggedConsumptionAsync(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("999")] // out of range numeric value
|
||||
[InlineData("not-a-media-kind")] // textual value that is not an enum member
|
||||
public async Task GetUserTagConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
(Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
await SeedTaggedConsumptionAsync(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);
|
||||
}
|
||||
|
||||
/// <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 tagged 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 tag.</returns>
|
||||
private async Task<string> SeedTaggedConsumptionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
// Tag names are the primary key of a shared table, so every seeded name carries a unique suffix.
|
||||
string tagName = $"tag-{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);
|
||||
TagEntity tag = _tagEntityFixture.Create(name: tagName);
|
||||
track.Tags.Add(tag);
|
||||
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 tagName;
|
||||
}
|
||||
|
||||
/// <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 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 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 tags 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();
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearResumePointsRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsRequestMappingTests
|
||||
{
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public ClearResumePointsRequestMappingTests()
|
||||
{
|
||||
_clearResumePointsRequestFixture = new ClearResumePointsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
ClearResumePointsCommand result = request.ToCommand(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
ClearResumePointsCommand result = request.ToCommand(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToCommand_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
ClearResumePointsCommand result = request.ToCommand(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics;
|
||||
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="GetAllUsersConsumptionStatisticsRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsRequestMappingTests
|
||||
{
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetAllUsersConsumptionStatisticsRequestMappingTests()
|
||||
{
|
||||
_getAllUsersConsumptionStatisticsRequestFixture = new GetAllUsersConsumptionStatisticsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Audiobook),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.NotNull(result.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Audiobook), result.MediaKind);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsQuery result = request.ToQuery();
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
|
||||
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="GetConsumptionStatisticsRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsRequestMappingTests
|
||||
{
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetConsumptionStatisticsRequestMappingTests()
|
||||
{
|
||||
_getConsumptionStatisticsRequestFixture = new GetConsumptionStatisticsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.MusicTrack),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.NotNull(result.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.MusicTrack), result.MediaKind);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
|
||||
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="GetMostConsumedRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedRequestMappingTests
|
||||
{
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetMostConsumedRequestMappingTests()
|
||||
{
|
||||
_getMostConsumedRequestFixture = new GetMostConsumedRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Movie),
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.NotNull(result.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Movie), result.MediaKind);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(3, paginationData.CurrentPage);
|
||||
Assert.Equal(25, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenCurrentPageAndPerPageAreNull_ShouldMapNullPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyCurrentPageIsSupplied_ShouldPreserveItAndDefaultPerPageToFifty()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: 4,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(4, paginationData.CurrentPage);
|
||||
Assert.Equal(50, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyPerPageIsSupplied_ShouldPreserveItAndDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
includeCurrentPage: false,
|
||||
perPage: 20);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(1, paginationData.CurrentPage);
|
||||
Assert.Equal(20, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenCurrentPageAndPerPageAreSupplied_ShouldPreserveBoth()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: 7,
|
||||
perPage: 15);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(7, paginationData.CurrentPage);
|
||||
Assert.Equal(15, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0, 1, 1)] // both at the lower boundary
|
||||
[InlineData(0, -5, 1, 1)] // zero current page with a negative page size
|
||||
[InlineData(-3, 10, 1, 10)] // negative current page with a valid page size
|
||||
[InlineData(-2, -7, 1, 1)] // both negative
|
||||
public void ToQuery_WhenCurrentPageOrPerPageIsNotPositive_ShouldClampOnlyTheInvalidValue(
|
||||
int currentPage,
|
||||
int perPage,
|
||||
int expectedCurrentPage,
|
||||
int expectedPerPage)
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: currentPage,
|
||||
perPage: perPage);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(expectedCurrentPage, paginationData.CurrentPage);
|
||||
Assert.Equal(expectedPerPage, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetMostConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
|
||||
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="GetRecentlyConsumedRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedRequestMappingTests
|
||||
{
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetRecentlyConsumedRequestMappingTests()
|
||||
{
|
||||
_getRecentlyConsumedRequestFixture = new GetRecentlyConsumedRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.TvEpisode),
|
||||
currentPage: 2,
|
||||
perPage: 40,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.NotNull(result.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.TvEpisode), result.MediaKind);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(2, paginationData.CurrentPage);
|
||||
Assert.Equal(40, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenCurrentPageAndPerPageAreNull_ShouldMapNullPaginationData()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.PaginationData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyCurrentPageIsSupplied_ShouldPreserveItAndDefaultPerPageToFifty()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: 5,
|
||||
includePerPage: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(5, paginationData.CurrentPage);
|
||||
Assert.Equal(50, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenOnlyPerPageIsSupplied_ShouldPreserveItAndDefaultCurrentPageToOne()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
includeCurrentPage: false,
|
||||
perPage: 30);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(1, paginationData.CurrentPage);
|
||||
Assert.Equal(30, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenCurrentPageAndPerPageAreSupplied_ShouldPreserveBoth()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: 9,
|
||||
perPage: 12);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(9, paginationData.CurrentPage);
|
||||
Assert.Equal(12, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 0, 1, 1)] // both at the lower boundary
|
||||
[InlineData(0, -5, 1, 1)] // zero current page with a negative page size
|
||||
[InlineData(-3, 10, 1, 10)] // negative current page with a valid page size
|
||||
[InlineData(-2, -7, 1, 1)] // both negative
|
||||
public void ToQuery_WhenCurrentPageOrPerPageIsNotPositive_ShouldClampOnlyTheInvalidValue(
|
||||
int currentPage,
|
||||
int perPage,
|
||||
int expectedCurrentPage,
|
||||
int expectedPerPage)
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: currentPage,
|
||||
perPage: perPage);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
PaginationDataDto paginationData = Assert.IsType<PaginationDataDto>(result.PaginationData);
|
||||
Assert.Equal(expectedCurrentPage, paginationData.CurrentPage);
|
||||
Assert.Equal(expectedPerPage, paginationData.PerPage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
|
||||
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="GetTagConsumptionRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionRequestMappingTests
|
||||
{
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetTagConsumptionRequestMappingTests()
|
||||
{
|
||||
_getTagConsumptionRequestFixture = new GetTagConsumptionRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.NotNull(result.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Book), result.MediaKind);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetTagConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+50
@@ -418,6 +418,54 @@ public class ValidatorUtilitiesTests
|
||||
result.ShouldNotHaveValidationError(s_nullableEnumValueError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTextualEnumValueIsNull_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(textualEnumValue: null);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(request);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(s_textualEnumValueError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(ValidatorUtilitiesTestEnum.First))] // the exact member name
|
||||
[InlineData("first")] // the member name in lower case
|
||||
[InlineData("SECOND")] // the member name in upper case
|
||||
public void Validate_WhenTextualEnumValueIsAMemberName_ShouldNotHaveValidationError(string textualEnumValue)
|
||||
{
|
||||
// Arrange
|
||||
ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(textualEnumValue: textualEnumValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(request);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(s_textualEnumValueError);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty value
|
||||
[InlineData(" ")] // a whitespace only value
|
||||
[InlineData("Unknown")] // a name that is not a member of the enumeration
|
||||
[InlineData("0")] // a number that is a defined member value, which must still be rejected
|
||||
[InlineData("1")] // another number that is a defined member value
|
||||
[InlineData("99")] // a number that is not a member value
|
||||
public void Validate_WhenTextualEnumValueIsNotAMemberName_ShouldHaveValidationError(string textualEnumValue)
|
||||
{
|
||||
// Arrange
|
||||
ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(textualEnumValue: textualEnumValue);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(request);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(s_textualEnumValueError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMaxLengthValueExceedsMaximumLength_ShouldHaveValidationError()
|
||||
{
|
||||
@@ -772,6 +820,7 @@ public class ValidatorUtilitiesTests
|
||||
RuleFor(request => request.NotEmptyCollectionValue).NotEmpty().WithError(s_notEmptyCollectionValueError);
|
||||
RuleFor(request => request.EnumValue).IsInEnum().WithError(s_enumValueError);
|
||||
RuleFor(request => request.NullableEnumValue).IsInEnum().WithError(s_nullableEnumValueError);
|
||||
RuleFor(request => request.TextualEnumValue).IsInEnum<ValidatorUtilitiesTestRequest, ValidatorUtilitiesTestEnum>().WithError(s_textualEnumValueError);
|
||||
RuleFor(request => request.MaxLengthValue).MaximumLength(5).WithError(s_maxLengthValueError);
|
||||
RuleFor(request => request.MinLengthValue).MinimumLength(3).WithError(s_minLengthValueError);
|
||||
RuleFor(request => request.ExactLengthValue).Length(3).WithError(s_exactLengthValueError);
|
||||
@@ -798,6 +847,7 @@ public class ValidatorUtilitiesTests
|
||||
private static readonly Error s_notEmptyCollectionValueError = Error.Validation(description: "NotEmptyCollectionValueError");
|
||||
private static readonly Error s_enumValueError = Error.Validation(description: "EnumValueError");
|
||||
private static readonly Error s_nullableEnumValueError = Error.Validation(description: "NullableEnumValueError");
|
||||
private static readonly Error s_textualEnumValueError = Error.Validation(description: "TextualEnumValueError");
|
||||
private static readonly Error s_maxLengthValueError = Error.Validation(description: "MaxLengthValueError");
|
||||
private static readonly Error s_minLengthValueError = Error.Validation(description: "MinLengthValueError");
|
||||
private static readonly Error s_exactLengthValueError = Error.Validation(description: "ExactLengthValueError");
|
||||
|
||||
+8
-4
@@ -125,9 +125,9 @@ public class GetAllUsersConsumptionStatisticsQueryHandlerTests
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
MediaKind mediaKind = MediaKind.MusicTrack;
|
||||
DateTime fromUtc = DateTime.UtcNow.AddDays(-10);
|
||||
DateTime toUtc = DateTime.UtcNow.AddDays(-1);
|
||||
string mediaKind = nameof(MediaKind.MusicTrack);
|
||||
string fromUtc = "2026-03-01T00:00:00Z";
|
||||
string toUtc = "2026-03-02T00:00:00Z";
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(
|
||||
libraryId: libraryId.ToString(),
|
||||
mediaKind: mediaKind,
|
||||
@@ -140,7 +140,11 @@ public class GetAllUsersConsumptionStatisticsQueryHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForAllUsersAsync(
|
||||
libraryId, mediaKind, fromUtc, toUtc, Arg.Any<CancellationToken>());
|
||||
libraryId,
|
||||
MediaKind.MusicTrack,
|
||||
Arg.Is<DateTime?>(value => value == new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)),
|
||||
Arg.Is<DateTime?>(value => value == new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+28
-12
@@ -81,7 +81,7 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(mediaKind: MediaKind.None);
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(mediaKind: nameof(MediaKind.None));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -94,7 +94,7 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(mediaKind: (MediaKind)99);
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(mediaKind: "999");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -104,11 +104,11 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack)] // a kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Book)] // another kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Movie)] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(MediaKind.Photo)] // a kind that every session counts for, still a defined kind
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(MediaKind mediaKind)
|
||||
[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
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(mediaKind: mediaKind);
|
||||
@@ -125,7 +125,7 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow.AddDays(-7),
|
||||
fromUtc: "2026-03-01T00:00:00Z",
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -140,7 +140,7 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(
|
||||
toUtc: DateTime.UtcNow,
|
||||
toUtc: "2026-03-02T00:00:00Z",
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -154,7 +154,7 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DateTime bound = DateTime.UtcNow;
|
||||
string bound = "2026-03-02T00:00:00Z";
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
@@ -169,8 +169,24 @@ public class GetAllUsersConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow,
|
||||
toUtc: DateTime.UtcNow.AddDays(-1));
|
||||
fromUtc: "2026-03-02T00:00:00Z",
|
||||
toUtc: "2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty bound
|
||||
[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 Validate_WhenADateRangeBoundIsNotAValidDate_ShouldHaveValidationError(string invalidBound)
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsQuery query = _getAllUsersConsumptionStatisticsQueryFixture.Create(fromUtc: invalidBound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+9
-4
@@ -198,9 +198,9 @@ public class GetConsumptionStatisticsQueryHandlerTests
|
||||
public async Task HandleAsync_WhenFiltersAreSupplied_ShouldForwardThemUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
MediaKind mediaKind = MediaKind.Book;
|
||||
DateTime fromUtc = DateTime.UtcNow.AddDays(-10);
|
||||
DateTime toUtc = DateTime.UtcNow.AddDays(-1);
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string fromUtc = "2026-03-01T00:00:00Z";
|
||||
string toUtc = "2026-03-02T00:00:00Z";
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(
|
||||
includeLibraryId: false,
|
||||
mediaKind: mediaKind,
|
||||
@@ -213,7 +213,12 @@ public class GetConsumptionStatisticsQueryHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
Arg.Any<Guid>(), null, mediaKind, fromUtc, toUtc, Arg.Any<CancellationToken>());
|
||||
Arg.Any<Guid>(),
|
||||
null,
|
||||
MediaKind.Book,
|
||||
Arg.Is<DateTime?>(value => value == new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)),
|
||||
Arg.Is<DateTime?>(value => value == new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+28
-12
@@ -124,7 +124,7 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(mediaKind: MediaKind.None);
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(mediaKind: nameof(MediaKind.None));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -137,7 +137,7 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(mediaKind: (MediaKind)99);
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(mediaKind: "999");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -147,11 +147,11 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack)] // a kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Book)] // another kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Movie)] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(MediaKind.Photo)] // a kind that every session counts for, still a defined kind
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(MediaKind mediaKind)
|
||||
[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
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(mediaKind: mediaKind);
|
||||
@@ -168,7 +168,7 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow.AddDays(-7),
|
||||
fromUtc: "2026-03-01T00:00:00Z",
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -183,7 +183,7 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(
|
||||
toUtc: DateTime.UtcNow,
|
||||
toUtc: "2026-03-02T00:00:00Z",
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -197,7 +197,7 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DateTime bound = DateTime.UtcNow;
|
||||
string bound = "2026-03-02T00:00:00Z";
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
@@ -212,8 +212,24 @@ public class GetConsumptionStatisticsQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow,
|
||||
toUtc: DateTime.UtcNow.AddDays(-1));
|
||||
fromUtc: "2026-03-02T00:00:00Z",
|
||||
toUtc: "2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty bound
|
||||
[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 Validate_WhenADateRangeBoundIsNotAValidDate_ShouldHaveValidationError(string invalidBound)
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsQuery query = _getConsumptionStatisticsQueryFixture.Create(fromUtc: invalidBound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+28
-12
@@ -124,7 +124,7 @@ public class GetMostConsumedQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(mediaKind: MediaKind.None);
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(mediaKind: nameof(MediaKind.None));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -137,7 +137,7 @@ public class GetMostConsumedQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(mediaKind: (MediaKind)99);
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(mediaKind: "999");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -147,11 +147,11 @@ public class GetMostConsumedQueryValidatorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack)] // a kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Book)] // another kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Movie)] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(MediaKind.Photo)] // a kind that every session counts for, still a defined kind
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(MediaKind mediaKind)
|
||||
[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
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(mediaKind: mediaKind);
|
||||
@@ -168,7 +168,7 @@ public class GetMostConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow.AddDays(-7),
|
||||
fromUtc: "2026-03-01T00:00:00Z",
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -183,7 +183,7 @@ public class GetMostConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(
|
||||
toUtc: DateTime.UtcNow,
|
||||
toUtc: "2026-03-02T00:00:00Z",
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -197,7 +197,7 @@ public class GetMostConsumedQueryValidatorTests
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DateTime bound = DateTime.UtcNow;
|
||||
string bound = "2026-03-02T00:00:00Z";
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
@@ -212,8 +212,24 @@ public class GetMostConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow,
|
||||
toUtc: DateTime.UtcNow.AddDays(-1));
|
||||
fromUtc: "2026-03-02T00:00:00Z",
|
||||
toUtc: "2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty bound
|
||||
[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 Validate_WhenADateRangeBoundIsNotAValidDate_ShouldHaveValidationError(string invalidBound)
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(fromUtc: invalidBound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+28
-12
@@ -124,7 +124,7 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(mediaKind: MediaKind.None);
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(mediaKind: nameof(MediaKind.None));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -137,7 +137,7 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(mediaKind: (MediaKind)99);
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(mediaKind: "999");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -147,11 +147,11 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack)] // a kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Book)] // another kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Movie)] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(MediaKind.Photo)] // a kind that every session counts for, still a defined kind
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(MediaKind mediaKind)
|
||||
[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
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(mediaKind: mediaKind);
|
||||
@@ -168,7 +168,7 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow.AddDays(-7),
|
||||
fromUtc: "2026-03-01T00:00:00Z",
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -183,7 +183,7 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(
|
||||
toUtc: DateTime.UtcNow,
|
||||
toUtc: "2026-03-02T00:00:00Z",
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -197,7 +197,7 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DateTime bound = DateTime.UtcNow;
|
||||
string bound = "2026-03-02T00:00:00Z";
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
@@ -212,8 +212,24 @@ public class GetRecentlyConsumedQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow,
|
||||
toUtc: DateTime.UtcNow.AddDays(-1));
|
||||
fromUtc: "2026-03-02T00:00:00Z",
|
||||
toUtc: "2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty bound
|
||||
[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 Validate_WhenADateRangeBoundIsNotAValidDate_ShouldHaveValidationError(string invalidBound)
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(fromUtc: invalidBound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+28
-12
@@ -124,7 +124,7 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsNone_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(mediaKind: MediaKind.None);
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(mediaKind: nameof(MediaKind.None));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -137,7 +137,7 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
public void Validate_WhenMediaKindIsUndefined_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(mediaKind: (MediaKind)99);
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(mediaKind: "999");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
@@ -147,11 +147,11 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack)] // a kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Book)] // another kind supported by the current catalogues
|
||||
[InlineData(MediaKind.Movie)] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(MediaKind.Photo)] // a kind that every session counts for, still a defined kind
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(MediaKind mediaKind)
|
||||
[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
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(mediaKind: mediaKind);
|
||||
@@ -168,7 +168,7 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow.AddDays(-7),
|
||||
fromUtc: "2026-03-01T00:00:00Z",
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -183,7 +183,7 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(
|
||||
toUtc: DateTime.UtcNow,
|
||||
toUtc: "2026-03-02T00:00:00Z",
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
@@ -197,7 +197,7 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DateTime bound = DateTime.UtcNow;
|
||||
string bound = "2026-03-02T00:00:00Z";
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
@@ -212,8 +212,24 @@ public class GetTagConsumptionQueryValidatorTests
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(
|
||||
fromUtc: DateTime.UtcNow,
|
||||
toUtc: DateTime.UtcNow.AddDays(-1));
|
||||
fromUtc: "2026-03-02T00:00:00Z",
|
||||
toUtc: "2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // an empty bound
|
||||
[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 Validate_WhenADateRangeBoundIsNotAValidDate_ShouldHaveValidationError(string invalidBound)
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionQuery query = _getTagConsumptionQueryFixture.Create(fromUtc: invalidBound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearResumePointsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsRequestTests
|
||||
{
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsRequestTests"/> class.
|
||||
/// </summary>
|
||||
public ClearResumePointsRequestTests()
|
||||
{
|
||||
_clearResumePointsRequestFixture = new ClearResumePointsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAGuidLibraryId()
|
||||
{
|
||||
// Act
|
||||
ClearResumePointsRequest sut = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.LibraryId);
|
||||
Assert.True(Guid.TryParse(sut.LibraryId, out Guid parsedLibraryId));
|
||||
Assert.NotEqual(Guid.Empty, parsedLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsSupplied_ShouldPreserveIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
ClearResumePointsRequest sut = _clearResumePointsRequestFixture.Create(libraryId: libraryId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId.ToString(), sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
ClearResumePointsRequest sut = _clearResumePointsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
ClearResumePointsRequest sut = _clearResumePointsRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAllUsersConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsRequestTests
|
||||
{
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetAllUsersConsumptionStatisticsRequestTests()
|
||||
{
|
||||
_getAllUsersConsumptionStatisticsRequestFixture = new GetAllUsersConsumptionStatisticsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.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.NotEqual(nameof(MediaKind.None), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
DateTime parsedFromUtc = DateTime.Parse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
DateTime parsedToUtc = DateTime.Parse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Audiobook),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Audiobook), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = "0001-01-01T00:00:00Z";
|
||||
string toUtc = "9999-12-31T23:59:59.9999999Z";
|
||||
|
||||
// Act
|
||||
GetAllUsersConsumptionStatisticsRequest sut = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsRequestTests
|
||||
{
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetConsumptionStatisticsRequestTests()
|
||||
{
|
||||
_getConsumptionStatisticsRequestFixture = new GetConsumptionStatisticsRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.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.NotEqual(nameof(MediaKind.None), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
DateTime parsedFromUtc = DateTime.Parse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
DateTime parsedToUtc = DateTime.Parse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.MusicTrack),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.MusicTrack), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = "0001-01-01T00:00:00Z";
|
||||
string toUtc = "9999-12-31T23:59:59.9999999Z";
|
||||
|
||||
// Act
|
||||
GetConsumptionStatisticsRequest sut = _getConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
#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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMostConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedRequestTests
|
||||
{
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetMostConsumedRequestTests()
|
||||
{
|
||||
_getMostConsumedRequestFixture = new GetMostConsumedRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.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.NotEqual(nameof(MediaKind.None), sut.MediaKind);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.True(sut.CurrentPage.Value > 0);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.True(sut.PerPage.Value > 0);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
DateTime parsedFromUtc = DateTime.Parse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
DateTime parsedToUtc = DateTime.Parse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Movie),
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Movie), sut.MediaKind);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.Equal(3, sut.CurrentPage.Value);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.Equal(25, sut.PerPage.Value);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCurrentPageIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includeCurrentPage: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.CurrentPage);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenPerPageIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includePerPage: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.PerPage);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenPaginationBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: 0,
|
||||
perPage: -5);
|
||||
|
||||
// Assert
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.Equal(0, sut.CurrentPage.Value);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.Equal(-5, sut.PerPage.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = "0001-01-01T00:00:00Z";
|
||||
string toUtc = "9999-12-31T23:59:59.9999999Z";
|
||||
|
||||
// Act
|
||||
GetMostConsumedRequest sut = _getMostConsumedRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
#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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetRecentlyConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedRequestTests
|
||||
{
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetRecentlyConsumedRequestTests()
|
||||
{
|
||||
_getRecentlyConsumedRequestFixture = new GetRecentlyConsumedRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.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.NotEqual(nameof(MediaKind.None), sut.MediaKind);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.True(sut.CurrentPage.Value > 0);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.True(sut.PerPage.Value > 0);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
DateTime parsedFromUtc = DateTime.Parse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
DateTime parsedToUtc = DateTime.Parse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.TvEpisode),
|
||||
currentPage: 4,
|
||||
perPage: 10,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.TvEpisode), sut.MediaKind);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.Equal(4, sut.CurrentPage.Value);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.Equal(10, sut.PerPage.Value);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCurrentPageIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includeCurrentPage: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.CurrentPage);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenPerPageIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includePerPage: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.PerPage);
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenPaginationBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: 0,
|
||||
perPage: -5);
|
||||
|
||||
// Assert
|
||||
Assert.True(sut.CurrentPage.HasValue);
|
||||
Assert.Equal(0, sut.CurrentPage.Value);
|
||||
Assert.True(sut.PerPage.HasValue);
|
||||
Assert.Equal(-5, sut.PerPage.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = "0001-01-01T00:00:00Z";
|
||||
string toUtc = "9999-12-31T23:59:59.9999999Z";
|
||||
|
||||
// Act
|
||||
GetRecentlyConsumedRequest sut = _getRecentlyConsumedRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
#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.Globalization;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTagConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionRequestTests
|
||||
{
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetTagConsumptionRequestTests()
|
||||
{
|
||||
_getTagConsumptionRequestFixture = new GetTagConsumptionRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.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.NotEqual(nameof(MediaKind.None), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
DateTime parsedFromUtc = DateTime.Parse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
DateTime parsedToUtc = DateTime.Parse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.Equal(nameof(MediaKind.Book), sut.MediaKind);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = "0001-01-01T00:00:00Z";
|
||||
string toUtc = "9999-12-31T23:59:59.9999999Z";
|
||||
|
||||
// Act
|
||||
GetTagConsumptionRequest sut = _getTagConsumptionRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
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.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<ClearConsumptionHistoryCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly ClearConsumptionHistoryEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearConsumptionHistoryEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<ClearConsumptionHistoryCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ClearConsumptionHistoryEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(result);
|
||||
Assert.Equal(Result.Deleted, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid];
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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"]);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "TargetUserIdIsInvalid" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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_WhenCalled_ShouldSendClearConsumptionHistoryCommandWithNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ClearConsumptionHistoryCommand>(command => command.TargetUserId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), 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(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
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.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserConsumptionHistoryEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<ClearConsumptionHistoryCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly ClearUserConsumptionHistoryEndpoint _sut;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearUserConsumptionHistoryEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<ClearConsumptionHistoryCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ClearUserConsumptionHistoryEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(result);
|
||||
Assert.Equal(Result.Deleted, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid];
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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"]);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "TargetUserIdIsInvalid" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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_WhenCalled_ShouldSendClearConsumptionHistoryCommandWithRouteUserId()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = userId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ClearConsumptionHistoryCommand>(command => command.TargetUserId == userId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("userId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ClearConsumptionHistoryCommand>(command => command.TargetUserId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearConsumptionHistoryCommand>(), 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(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
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.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<ClearResumePointsCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly ClearResumePointsEndpoint _sut;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearResumePointsEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<ClearResumePointsCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ClearResumePointsEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.MediaResumePointNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.Library.LibraryIdCannotBeEmpty];
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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"]);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "LibraryIdCannotBeEmpty" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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_WhenCalled_ShouldSendClearResumePointsCommandWithMappedRequestAndNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(libraryId: libraryId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ClearResumePointsCommand>(command =>
|
||||
command.TargetUserId == null &&
|
||||
command.LibraryId == libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdIsNotProvided_ShouldSendCommandWithNullLibraryId()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(includeLibraryId: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ClearResumePointsCommand>(command =>
|
||||
command.TargetUserId == null &&
|
||||
command.LibraryId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
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.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserResumePointsEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<ClearResumePointsCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly ClearUserResumePointsEndpoint _sut;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearUserResumePointsEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<ClearResumePointsCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ClearUserResumePointsEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.Library.LibraryIdCannotBeEmpty];
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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", "LibraryIdCannotBeEmpty" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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_WhenCalled_ShouldSendClearResumePointsCommandWithRouteUserIdAndMappedRequest()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(libraryId: libraryId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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<ClearResumePointsCommand>(command =>
|
||||
command.TargetUserId == userId.ToString() &&
|
||||
command.LibraryId == libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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<ClearResumePointsCommand>(command =>
|
||||
command.TargetUserId == null &&
|
||||
command.LibraryId == request.LibraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ClearResumePointsCommand>(), 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);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user