From 968061e89aae06738505fc489f8ae4c8a4c89c06 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Wed, 28 Oct 2026 10:07:57 +0200 Subject: [PATCH] Implements tests for commit dfd979ec1ef54c538d8496841419efc304d4c929 --- .../statistics/Api.LibraryStatistics.md | 16 +- .../GetMostConsumedRequestMapping.cs | 9 +- .../GetRecentlyConsumedRequestMapping.cs | 9 +- .../Common/Utilities/ValidatorUtilities.cs | 18 + .../GetAllUsersConsumptionStatisticsQuery.cs | 14 +- ...lUsersConsumptionStatisticsQueryHandler.cs | 6 +- ...sersConsumptionStatisticsQueryValidator.cs | 41 +- .../GetConsumptionStatisticsQuery.cs | 14 +- .../GetConsumptionStatisticsQueryHandler.cs | 6 +- .../GetConsumptionStatisticsQueryValidator.cs | 41 +- .../GetMostConsumed/GetMostConsumedQuery.cs | 14 +- .../GetMostConsumedQueryHandler.cs | 6 +- .../GetMostConsumedQueryValidator.cs | 41 +- .../GetRecentlyConsumedQuery.cs | 14 +- .../GetRecentlyConsumedQueryHandler.cs | 6 +- .../GetRecentlyConsumedQueryValidator.cs | 41 +- .../GetTagConsumptionQuery.cs | 14 +- .../GetTagConsumptionQueryHandler.cs | 6 +- .../GetTagConsumptionQueryValidator.cs | 41 +- ...GetAllUsersConsumptionStatisticsRequest.cs | 14 +- .../GetConsumptionStatisticsRequest.cs | 14 +- .../GetMostConsumedRequest.cs | 14 +- .../GetRecentlyConsumedRequest.cs | 14 +- .../GetTagConsumptionRequest.cs | 14 +- ...ersConsumptionStatisticsEndpointSummary.cs | 6 +- ...GetConsumptionStatisticsEndpointSummary.cs | 6 +- ...serConsumptionStatisticsEndpointSummary.cs | 6 +- .../GetMostConsumedEndpointSummary.cs | 8 +- .../GetUserMostConsumedEndpointSummary.cs | 8 +- .../GetRecentlyConsumedEndpointSummary.cs | 8 +- .../GetUserRecentlyConsumedEndpointSummary.cs | 8 +- .../GetTagConsumptionEndpointSummary.cs | 6 +- .../GetUserTagConsumptionEndpointSummary.cs | 6 +- .../ValidatorUtilitiesTestRequest.cs | 3 +- .../ValidatorUtilitiesTestRequestFixture.cs | 7 +- ...lUsersConsumptionStatisticsQueryFixture.cs | 21 +- .../GetConsumptionStatisticsQueryFixture.cs | 21 +- .../GetMostConsumedQueryFixture.cs | 21 +- .../GetRecentlyConsumedQueryFixture.cs | 21 +- .../GetTagConsumptionQueryFixture.cs | 21 +- .../ClearResumePointsRequestFixture.cs | 42 ++ ...sersConsumptionStatisticsRequestFixture.cs | 74 ++ .../GetConsumptionStatisticsRequestFixture.cs | 74 ++ .../GetMostConsumedRequestFixture.cs | 84 +++ .../GetRecentlyConsumedRequestFixture.cs | 84 +++ .../GetTagConsumptionRequestFixture.cs | 74 ++ .../ClearConsumptionHistoryEndpointTests.cs | 357 ++++++++++ ...learUserConsumptionHistoryEndpointTests.cs | 367 ++++++++++ .../ClearResumePointsEndpointTests.cs | 389 +++++++++++ .../ClearUserResumePointsEndpointTests.cs | 458 +++++++++++++ .../DeleteConsumptionRecordEndpointTests.cs | 418 ++++++++++++ ...eleteUserConsumptionRecordEndpointTests.cs | 401 +++++++++++ ...UsersConsumptionStatisticsEndpointTests.cs | 567 ++++++++++++++++ .../GetConsumptionStatisticsEndpointTests.cs | 540 +++++++++++++++ ...tUserConsumptionStatisticsEndpointTests.cs | 413 +++++++++++ .../GetMostConsumedEndpointTests.cs | 550 +++++++++++++++ .../GetUserMostConsumedEndpointTests.cs | 473 +++++++++++++ .../GetRecentlyConsumedEndpointTests.cs | 639 ++++++++++++++++++ .../GetUserRecentlyConsumedEndpointTests.cs | 498 ++++++++++++++ .../GetTagConsumptionEndpointTests.cs | 496 ++++++++++++++ .../GetUserTagConsumptionEndpointTests.cs | 459 +++++++++++++ .../ClearConsumptionHistoryEndpointTests.cs | 376 +++++++++++ ...learUserConsumptionHistoryEndpointTests.cs | 505 ++++++++++++++ .../ClearResumePointsEndpointTests.cs | 431 ++++++++++++ .../ClearUserResumePointsEndpointTests.cs | 567 ++++++++++++++++ .../DeleteConsumptionRecordEndpointTests.cs | 440 ++++++++++++ ...eleteUserConsumptionRecordEndpointTests.cs | 526 ++++++++++++++ ...UsersConsumptionStatisticsEndpointTests.cs | 418 ++++++++++++ .../GetConsumptionStatisticsEndpointTests.cs | 392 +++++++++++ ...tUserConsumptionStatisticsEndpointTests.cs | 461 +++++++++++++ .../GetMostConsumedEndpointTests.cs | 389 +++++++++++ .../GetUserMostConsumedEndpointTests.cs | 487 +++++++++++++ .../GetRecentlyConsumedEndpointTests.cs | 375 ++++++++++ .../GetUserRecentlyConsumedEndpointTests.cs | 473 +++++++++++++ .../GetTagConsumptionEndpointTests.cs | 381 +++++++++++ .../GetUserTagConsumptionEndpointTests.cs | 480 +++++++++++++ .../ClearResumePointsRequestMappingTests.cs | 69 ++ ...onsumptionStatisticsRequestMappingTests.cs | 108 +++ ...onsumptionStatisticsRequestMappingTests.cs | 123 ++++ .../GetMostConsumedRequestMappingTests.cs | 220 ++++++ .../GetRecentlyConsumedRequestMappingTests.cs | 220 ++++++ .../GetTagConsumptionRequestMappingTests.cs | 123 ++++ .../Utilities/ValidatorUtilitiesTests.cs | 50 ++ ...sConsumptionStatisticsQueryHandlerTests.cs | 12 +- ...onsumptionStatisticsQueryValidatorTests.cs | 40 +- ...tConsumptionStatisticsQueryHandlerTests.cs | 13 +- ...onsumptionStatisticsQueryValidatorTests.cs | 40 +- .../GetMostConsumedQueryValidatorTests.cs | 40 +- .../GetRecentlyConsumedQueryValidatorTests.cs | 40 +- .../GetTagConsumptionQueryValidatorTests.cs | 40 +- .../ClearResumePointsRequestTests.cs | 70 ++ ...lUsersConsumptionStatisticsRequestTests.cs | 142 ++++ .../GetConsumptionStatisticsRequestTests.cs | 142 ++++ .../GetMostConsumedRequestTests.cs | 189 ++++++ .../GetRecentlyConsumedRequestTests.cs | 189 ++++++ .../GetTagConsumptionRequestTests.cs | 142 ++++ .../ClearConsumptionHistoryEndpointTests.cs | 179 +++++ ...learUserConsumptionHistoryEndpointTests.cs | 205 ++++++ .../ClearResumePointsEndpointTests.cs | 212 ++++++ .../ClearUserResumePointsEndpointTests.cs | 222 ++++++ .../DeleteConsumptionRecordEndpointTests.cs | 209 ++++++ ...eleteUserConsumptionRecordEndpointTests.cs | 219 ++++++ ...UsersConsumptionStatisticsEndpointTests.cs | 232 +++++++ .../GetConsumptionStatisticsEndpointTests.cs | 234 +++++++ ...tUserConsumptionStatisticsEndpointTests.cs | 239 +++++++ .../GetMostConsumedEndpointTests.cs | 246 +++++++ .../GetUserMostConsumedEndpointTests.cs | 279 ++++++++ .../GetRecentlyConsumedEndpointTests.cs | 246 +++++++ .../GetUserRecentlyConsumedEndpointTests.cs | 278 ++++++++ .../GetTagConsumptionEndpointTests.cs | 234 +++++++ .../GetUserTagConsumptionEndpointTests.cs | 239 +++++++ 111 files changed, 19955 insertions(+), 292 deletions(-) create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/ClearResumePointsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetConsumptionStatisticsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetMostConsumedRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetRecentlyConsumedRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetTagConsumptionRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/ClearResumePointsRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetMostConsumedRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMappingTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/ClearResumePointsRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetConsumptionStatisticsRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetMostConsumedRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetRecentlyConsumedRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetTagConsumptionRequestTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs diff --git a/docs/technical/api/library/statistics/Api.LibraryStatistics.md b/docs/technical/api/library/statistics/Api.LibraryStatistics.md index 7dbc7d78..3854f851 100644 --- a/docs/technical/api/library/statistics/Api.LibraryStatistics.md +++ b/docs/technical/api/library/statistics/Api.LibraryStatistics.md @@ -81,11 +81,11 @@ Authorization: Bearer | 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 | 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 diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs index 03349cd7..68119459 100644 --- a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs @@ -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 + ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs index 5f06a893..5b92c9ee 100644 --- a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs @@ -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 + ); } } diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs index f4ffb337..27bc9a0e 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -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)); } + /// + /// Defines a validation rule that ensures a textual enum value is either or the name of a defined member of the specified + /// enumeration type. + /// + /// + /// Only the member names of the enumeration are accepted, so a numeric value is rejected even when it is a defined member. A + /// value represents an omitted optional filter and passes. + /// + /// The type of the request being validated. + /// The type of the enumeration. + /// The rule builder instance. + /// The current instance for method chaining. + public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum + { + return ruleBuilder.Must(value => value is null || Enum.GetNames().Contains(value, StringComparer.OrdinalIgnoreCase)); + } + /// /// Defines a validation rule that ensures the string property does not exceed the specified maximum length. /// diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs index fb35725e..5d0a2166 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -11,13 +9,13 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptio /// Query for getting the consumption statistics of every user. /// /// The Id of the media library to restrict the statistics to, or for every library. -/// The kind of media to restrict the statistics to, or for every kind. -/// The inclusive start of the date range, or when the range has no start. -/// The inclusive end of the date range, or when the range has no end. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. [DebuggerDisplay("MediaKind: {MediaKind}")] public record GetAllUsersConsumptionStatisticsQuery( string? LibraryId, - MediaKind? MediaKind, - DateTime? FromUtc, - DateTime? ToUtc + string? MediaKind, + string? FromUtc, + string? ToUtc ) : IQuery; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs index d28f9ad6..f8614720 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandler.cs @@ -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(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> 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; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs index 7ff35ef6..477bc71b 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; +using System.Globalization; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.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() .WithError(Errors.MediaConsumption.UnsupportedMediaKind); - // An inverted range would silently return no records, so it is rejected as an invalid request instead. + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. RuleFor(query => query.FromUtc) - .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); } } diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs index 0a13267d..34b63d68 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -12,14 +10,14 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatist /// /// The Id of the user whose statistics are retrieved, or for the current user. /// The Id of the media library to restrict the statistics to, or for every library. -/// The kind of media to restrict the statistics to, or for every kind. -/// The inclusive start of the date range, or when the range has no start. -/// The inclusive end of the date range, or when the range has no end. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. [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; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs index a0299133..812f62f0 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandler.cs @@ -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(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> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository - .GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false); + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); if (getRecordsResult.IsFailure) return getRecordsResult.Errors; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs index 813ec466..4a51faeb 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; +using System.Globalization; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; @@ -29,18 +30,42 @@ public class GetConsumptionStatisticsQueryValidator : AbstractValidator query.MediaKind) - .IsInEnum() - .WithError(Errors.MediaConsumption.UnsupportedMediaKind) - .When(query => query.MediaKind is not null); - - RuleFor(query => query.MediaKind) - .Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None) + .IsInEnum() .WithError(Errors.MediaConsumption.UnsupportedMediaKind); - // An inverted range would silently return no records, so it is rejected as an invalid request instead. + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. RuleFor(query => query.FromUtc) - .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); } } diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs index 7eeffc81..3b0053fb 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs @@ -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; /// /// The Id of the user whose history is retrieved, or for the current user. /// The Id of the media library to restrict the history to, or for every library. -/// The kind of media to restrict the history to, or for every kind. -/// The inclusive start of the date range, or when the range has no start. -/// The inclusive end of the date range, or when the range has no end. +/// The name of the kind of media to restrict the history to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. /// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned. [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; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs index 7db28a78..4c3d5a81 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs @@ -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(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository - .GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false); + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); if (getRecordsResult.IsFailure) return getRecordsResult.Errors; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs index 7d010cf8..1e5ada9d 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; +using System.Globalization; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; @@ -29,18 +30,42 @@ public class GetMostConsumedQueryValidator : AbstractValidator query.MediaKind) - .IsInEnum() - .WithError(Errors.MediaConsumption.UnsupportedMediaKind) - .When(query => query.MediaKind is not null); - - RuleFor(query => query.MediaKind) - .Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None) + .IsInEnum() .WithError(Errors.MediaConsumption.UnsupportedMediaKind); - // An inverted range would silently return no records, so it is rejected as an invalid request instead. + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. RuleFor(query => query.FromUtc) - .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); } } diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs index e0ac673b..68503691 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs @@ -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; /// /// The Id of the user whose history is retrieved, or for the current user. /// The Id of the media library to restrict the history to, or for every library. -/// The kind of media to restrict the history to, or for every kind. -/// The inclusive start of the date range, or when the range has no start. -/// The inclusive end of the date range, or when the range has no end. +/// The name of the kind of media to restrict the history to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. /// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned. [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; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs index 4980b879..118140f4 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs @@ -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(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository - .GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false); + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); if (getRecordsResult.IsFailure) return getRecordsResult.Errors; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs index 241ac8ee..3bebfb33 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; +using System.Globalization; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; @@ -29,18 +30,42 @@ public class GetRecentlyConsumedQueryValidator : AbstractValidator query.MediaKind) - .IsInEnum() - .WithError(Errors.MediaConsumption.UnsupportedMediaKind) - .When(query => query.MediaKind is not null); - - RuleFor(query => query.MediaKind) - .Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None) + .IsInEnum() .WithError(Errors.MediaConsumption.UnsupportedMediaKind); - // An inverted range would silently return no records, so it is rejected as an invalid request instead. + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. RuleFor(query => query.FromUtc) - .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); } } diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs index 8ef7edd1..1abff580 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs @@ -1,7 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -12,14 +10,14 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; /// /// The Id of the user whose statistics are retrieved, or for the current user. /// The Id of the media library to restrict the statistics to, or for every library. -/// The kind of media to restrict the statistics to, or for every kind. -/// The inclusive start of the date range, or when the range has no start. -/// The inclusive end of the date range, or when the range has no end. +/// The name of the kind of media to restrict the statistics to, or for every kind. +/// The inclusive start of the date range, in UTC, or when the range has no start. +/// The inclusive end of the date range, in UTC, or when the range has no end. [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; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs index 41fa0e7d..24c5792a 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs @@ -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(query.MediaKind, ignoreCase: true); + DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository - .GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false); + .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false); if (getRecordsResult.IsFailure) return getRecordsResult.Errors; diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs index 5510b2da..3c7bf4e1 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidator.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; +using System.Globalization; #endregion namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; @@ -29,18 +30,42 @@ public class GetTagConsumptionQueryValidator : AbstractValidator query.MediaKind) - .IsInEnum() - .WithError(Errors.MediaConsumption.UnsupportedMediaKind) - .When(query => query.MediaKind is not null); - - RuleFor(query => query.MediaKind) - .Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None) + .IsInEnum() .WithError(Errors.MediaConsumption.UnsupportedMediaKind); - // An inverted range would silently return no records, so it is rejected as an invalid request instead. + RuleFor(query => query.MediaKind) + .Must(mediaKind => mediaKind is null || + !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase)) + .WithError(Errors.MediaConsumption.UnsupportedMediaKind); + + // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead. RuleFor(query => query.FromUtc) - .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value) + .Must(fromUtc => fromUtc is null || DateTime.TryParse( + fromUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.ToUtc) + .Must(toUtc => toUtc is null || DateTime.TryParse( + toUtc, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out _)) + .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); + + RuleFor(query => query.FromUtc) + .Must((query, fromUtc) => + { + if (fromUtc is null || query.ToUtc is null || + !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) || + !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc)) + return true; + return parsedFromUtc <= parsedToUtc; + }) .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid); } } diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs index 760da069..05aca708 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequest.cs @@ -1,6 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -10,13 +8,13 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// Represents a request for getting the consumption statistics of every user. /// /// The Id of the media library to restrict the statistics to. Optional. -/// The kind of media to restrict the statistics to. Optional. -/// The inclusive start of the date range. Optional. -/// The inclusive end of the date range. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. [DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] public sealed record GetAllUsersConsumptionStatisticsRequest( string? LibraryId, - MediaKind? MediaKind, - DateTime? FromUtc, - DateTime? ToUtc + string? MediaKind, + string? FromUtc, + string? ToUtc ); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs index 58817188..2b744907 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetConsumptionStatisticsRequest.cs @@ -1,6 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -10,13 +8,13 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// Represents a request for getting the consumption statistics of a user. /// /// The Id of the media library to restrict the statistics to. Optional. -/// The kind of media to restrict the statistics to. Optional. -/// The inclusive start of the date range. Optional. -/// The inclusive end of the date range. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. [DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] public sealed record GetConsumptionStatisticsRequest( string? LibraryId, - MediaKind? MediaKind, - DateTime? FromUtc, - DateTime? ToUtc + string? MediaKind, + string? FromUtc, + string? ToUtc ); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs index e754cd9d..153ea40d 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs @@ -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. /// /// The Id of the media library to restrict the history to. Optional. -/// The kind of media to restrict the history to. Optional. +/// The name of the kind of media to restrict the history to. Optional. /// The one based page of media items to return. Optional. /// The number of media items per page. Optional. -/// The inclusive start of the date range. Optional. -/// The inclusive end of the date range. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. [DebuggerDisplay("MediaKind: {MediaKind}; 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 ); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs index a32ec62f..223c549f 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs @@ -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. /// /// The Id of the media library to restrict the history to. Optional. -/// The kind of media to restrict the history to. Optional. +/// The name of the kind of media to restrict the history to. Optional. /// The one based page of media items to return. Optional. /// The number of media items per page. Optional. -/// The inclusive start of the date range. Optional. -/// The inclusive end of the date range. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. [DebuggerDisplay("MediaKind: {MediaKind}; 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 ); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs index bcffa4d9..336f1ad8 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs @@ -1,6 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Diagnostics; #endregion @@ -10,13 +8,13 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// Represents a request for getting the consumption statistics of the tags of a user. /// /// The Id of the media library to restrict the statistics to. Optional. -/// The kind of media to restrict the statistics to. Optional. -/// The inclusive start of the date range. Optional. -/// The inclusive end of the date range. Optional. +/// The name of the kind of media to restrict the statistics to. Optional. +/// The inclusive start of the date range, in UTC, as a text value. Optional. +/// The inclusive end of the date range, in UTC, as a text value. Optional. [DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")] public sealed record GetTagConsumptionRequest( string? LibraryId, - MediaKind? MediaKind, - DateTime? FromUtc, - DateTime? ToUtc + string? MediaKind, + string? FromUtc, + string? ToUtc ); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs index 66586588..975f397d 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs @@ -27,12 +27,12 @@ public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs index cb64c0ee..0fa1d4ee 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs @@ -27,12 +27,12 @@ public class GetConsumptionStatisticsEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs index 7d41eff3..9ffd43e8 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs @@ -27,13 +27,13 @@ public class GetUserConsumptionStatisticsEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs index cf7aa224..0c02ec57 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs @@ -27,15 +27,15 @@ public class GetMostConsumedEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs index 36c4dd20..efca6d28 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointSummary.cs @@ -27,16 +27,16 @@ public class GetUserMostConsumedEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs index 9faf5695..f73719c7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs @@ -27,15 +27,15 @@ public class GetRecentlyConsumedEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs index 6189a329..2ebbcc2b 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointSummary.cs @@ -27,16 +27,16 @@ public class GetUserRecentlyConsumedEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs index ef8ebdb5..af3a686c 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs @@ -26,12 +26,12 @@ public class GetTagConsumptionEndpointSummary : Summary 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."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs index 068fc130..f7871137 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs @@ -26,13 +26,13 @@ public class GetUserTagConsumptionEndpointSummary : Summary 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."); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs index 443bf52c..b31ea1e9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs @@ -35,4 +35,5 @@ public sealed record ValidatorUtilitiesTestRequest( int InclusiveIntValue, int? InclusiveNullableIntValue, string? EqualValue, - string? EqualComparisonValue); + string? EqualComparisonValue, + string? TextualEnumValue); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs index 29b8f426..db7cd22f 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs @@ -44,6 +44,7 @@ public class ValidatorUtilitiesTestRequestFixture /// Optional. The nullable integer value that must be between 1 and 10. /// Optional. The value that must equal the comparison value. /// Optional. The comparison value. + /// Optional. The textual enum value that must be a member name of the test enumeration. /// A configured instance. 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() @@ -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().ToString())) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryFixture.cs index 9cdcb7cf..f5f4ac9e 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryFixture.cs @@ -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 . /// /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. - /// Optional. The kind of media to restrict the statistics to. Defaults to a random supported kind. - /// Optional. The inclusive start of the date range. Defaults to a bounded moment in the past. - /// Optional. The inclusive end of the date range. Defaults to a bounded moment after the start. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. /// Whether the library Id should be included, or forced to . /// Whether the media kind should be included, or forced to . /// Whether the start of the date range should be included, or forced to . @@ -43,22 +44,20 @@ public class GetAllUsersConsumptionStatisticsQueryFixture /// The created . 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); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryFixture.cs index f2664c3f..27979ab9 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryFixture.cs @@ -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 /// /// Optional. The Id of the user whose statistics are retrieved. Defaults to a random Id. /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. - /// Optional. The kind of media to restrict the statistics to. Defaults to a random supported kind. - /// Optional. The inclusive start of the date range. Defaults to a bounded moment in the past. - /// Optional. The inclusive end of the date range. Defaults to a bounded moment after the start. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. /// Whether the target user Id should be included, or forced to . /// Whether the library Id should be included, or forced to . /// Whether the media kind should be included, or forced to . @@ -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); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryFixture.cs index ee7cecbc..1a889a33 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryFixture.cs @@ -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 /// /// Optional. The Id of the user whose history is retrieved. Defaults to a random Id. /// Optional. The Id of the media library to restrict the history to. Defaults to a random Id. - /// Optional. The kind of media to restrict the history to. Defaults to a random supported kind. - /// Optional. The inclusive start of the date range. Defaults to a bounded moment in the past. - /// Optional. The inclusive end of the date range. Defaults to a bounded moment after the start. + /// Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. /// Optional. The requested pagination data. Defaults to a random page when it is included. /// Whether the target user Id should be included, or forced to . /// Whether the library Id should be included, or forced to . @@ -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); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryFixture.cs index 1f0ca2a8..47546ccb 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryFixture.cs @@ -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 /// /// Optional. The Id of the user whose history is retrieved. Defaults to a random Id. /// Optional. The Id of the media library to restrict the history to. Defaults to a random Id. - /// Optional. The kind of media to restrict the history to. Defaults to a random supported kind. - /// Optional. The inclusive start of the date range. Defaults to a bounded moment in the past. - /// Optional. The inclusive end of the date range. Defaults to a bounded moment after the start. + /// Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. /// Optional. The requested pagination data. Defaults to a random page when it is included. /// Whether the target user Id should be included, or forced to . /// Whether the library Id should be included, or forced to . @@ -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); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryFixture.cs index 2fe7435c..c80358d8 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryFixture.cs @@ -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 /// /// Optional. The Id of the user whose statistics are retrieved. Defaults to a random Id. /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. - /// Optional. The kind of media to restrict the statistics to. Defaults to a random supported kind. - /// Optional. The inclusive start of the date range. Defaults to a bounded moment in the past. - /// Optional. The inclusive end of the date range. Defaults to a bounded moment after the start. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. /// Whether the target user Id should be included, or forced to . /// Whether the library Id should be included, or forced to . /// Whether the media kind should be included, or forced to . @@ -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); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/ClearResumePointsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/ClearResumePointsRequestFixture.cs new file mode 100644 index 00000000..03ede8e3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/ClearResumePointsRequestFixture.cs @@ -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; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the deletion to. Defaults to a random Id. + /// Whether the library Id should be included, or forced to . + /// The created . + public ClearResumePointsRequest Create( + string? libraryId = null, + bool includeLibraryId = true) + { + return new ClearResumePointsRequest( + includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestFixture.cs new file mode 100644 index 00000000..9bfd6bd6 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestFixture.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; + +/// +/// Fixture class for the record. +/// +[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 + ]; + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. + /// Whether the library Id should be included, or forced to . + /// Whether the media kind name should be included, or forced to . + /// Whether the start of the date range should be included, or forced to . + /// Whether the end of the date range should be included, or forced to . + /// The created . + public 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); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetConsumptionStatisticsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetConsumptionStatisticsRequestFixture.cs new file mode 100644 index 00000000..f85f3b31 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetConsumptionStatisticsRequestFixture.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; + +/// +/// Fixture class for the record. +/// +[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 + ]; + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. + /// Whether the library Id should be included, or forced to . + /// Whether the media kind name should be included, or forced to . + /// Whether the start of the date range should be included, or forced to . + /// Whether the end of the date range should be included, or forced to . + /// The created . + public 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); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetMostConsumedRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetMostConsumedRequestFixture.cs new file mode 100644 index 00000000..c33ec59d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetMostConsumedRequestFixture.cs @@ -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; + +/// +/// Fixture class for the record. +/// +[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 + ]; + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the history to. Defaults to a random Id. + /// Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind. + /// Optional. The one based page of media items to return. Defaults to a bounded positive page. + /// Optional. The number of media items per page. Defaults to a bounded positive count. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. + /// Whether the library Id should be included, or forced to . + /// Whether the media kind name should be included, or forced to . + /// Whether the current page should be included, or forced to . + /// Whether the count per page should be included, or forced to . + /// Whether the start of the date range should be included, or forced to . + /// Whether the end of the date range should be included, or forced to . + /// The created . + public 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); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetRecentlyConsumedRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetRecentlyConsumedRequestFixture.cs new file mode 100644 index 00000000..a1737f7a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetRecentlyConsumedRequestFixture.cs @@ -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; + +/// +/// Fixture class for the record. +/// +[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 + ]; + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the history to. Defaults to a random Id. + /// Optional. The name of the kind of media to restrict the history to. Defaults to the name of a random supported kind. + /// Optional. The one based page of media items to return. Defaults to a bounded positive page. + /// Optional. The number of media items per page. Defaults to a bounded positive count. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. + /// Whether the library Id should be included, or forced to . + /// Whether the media kind name should be included, or forced to . + /// Whether the current page should be included, or forced to . + /// Whether the count per page should be included, or forced to . + /// Whether the start of the date range should be included, or forced to . + /// Whether the end of the date range should be included, or forced to . + /// The created . + public 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); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetTagConsumptionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetTagConsumptionRequestFixture.cs new file mode 100644 index 00000000..1e8e7bde --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetTagConsumptionRequestFixture.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; + +/// +/// Fixture class for the record. +/// +[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 + ]; + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id. + /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind. + /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value. + /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment, as a text value. + /// Whether the library Id should be included, or forced to . + /// Whether the media kind name should be included, or forced to . + /// Whether the start of the date range should be included, or forced to . + /// Whether the end of the date range should be included, or forced to . + /// The created . + public 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); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..5f676d74 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearConsumptionHistoryEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ClearConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the media item to resume. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..9e968f18 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserConsumptionHistoryEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ClearUserConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs new file mode 100644 index 00000000..66467c75 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ClearResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the media item to resume. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the resume points identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be deleted. + private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs new file mode 100644 index 00000000..917e1ebb --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserResumePointsEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ClearUserResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the media item to resume. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the resume points identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be deleted. + private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..bd43439e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionRecordEndpointTests : IClassFixture, IAsyncLifetime +{ + private static readonly DateTime s_startedOnUtc = new(2026, 4, 2, 20, 15, 0, DateTimeKind.Utc); + private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 2, 20, 45, 0, DateTimeKind.Utc); + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the media item to resume. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..b3935cbf --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteUserConsumptionRecordEndpointTests : IClassFixture, IAsyncLifetime +{ + private static readonly DateTime s_startedOnUtc = new(2026, 4, 3, 18, 5, 0, DateTimeKind.Utc); + private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 3, 18, 40, 0, DateTimeKind.Utc); + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteUserConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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); + } + + /// + /// Seeds a media library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed media item. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The Id of the seeded record. + private async Task SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..48206f5d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetAllUsersConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated admin API client. + /// + 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(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? problemDetails = JsonSerializer.Deserialize>(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(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(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(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(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"); + } + + /// + /// Asserts that the combined totals are exactly the sum of the returned user summaries. + /// + /// The all users statistics response to assert on. + 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 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); + } + } + + /// + /// Seeds a user with a music library and two counted music sessions. + /// + /// The Ids of the seeded user and of its music library. + 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); + } + + /// + /// Seeds a user with an ebook library and one counted book session and one uncounted one. + /// + /// The Ids of the seeded user and of its ebook library. + 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); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: startedOnUtc, + lastActivityOnUtc: startedOnUtc.AddMinutes(1), + endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2), + consumedDurationMilliseconds: consumedDurationMilliseconds, + lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset, + lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0, + lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null, + lastProgressFraction: 0, + consecutivePagesRead: consecutivePagesRead); + dbContext.MediaConsumptionRecords.Add(record); + await dbContext.SaveChangesAsync(); + return recordId; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + /// + /// 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. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.MediaConsumptionRecords.ExecuteDeleteAsync(); + await dbContext.Libraries.ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..b2d18fe3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs @@ -0,0 +1,540 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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(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(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(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(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(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(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(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(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); + } + + /// + /// Seeds a music library and an ebook library owned by , with one track and one book history. + /// + /// The Id of the user that owns the libraries and the consumption records. + /// The Ids of the music library and the ebook library. + 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); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: startedOnUtc, + lastActivityOnUtc: startedOnUtc.AddMinutes(1), + endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2), + consumedDurationMilliseconds: consumedDurationMilliseconds, + lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset, + lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0, + lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null, + lastProgressFraction: 0, + consecutivePagesRead: consecutivePagesRead); + dbContext.MediaConsumptionRecords.Add(record); + await dbContext.SaveChangesAsync(); + return recordId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..289747c3 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserConsumptionStatisticsEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetUserConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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(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? problemDetails = JsonSerializer.Deserialize>(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(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"); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: startedOnUtc, + lastActivityOnUtc: startedOnUtc.AddMinutes(1), + endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2), + consumedDurationMilliseconds: consumedDurationMilliseconds, + lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset, + lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0, + lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null, + lastProgressFraction: 0, + consecutivePagesRead: consecutivePagesRead); + dbContext.MediaConsumptionRecords.Add(record); + await dbContext.SaveChangesAsync(); + return recordId; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs new file mode 100644 index 00000000..c334556e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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"); + } + + /// + /// Seeds two tracks with three and two sessions and a book with two sessions, all owned by . + /// + /// The Id of the user that owns the libraries and the consumption records. + /// The Ids of the music library, both tracks, the ebook library, and the book. + 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); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a track of , together with its artist and album. + /// + /// The Id of the library that owns the track. + /// The title of the track. + /// The title of the album that contains the track. + /// The name of the artist of the album. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false)); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a book of , together with an author contributor when a name is supplied. + /// + /// The Id of the library that owns the book. + /// The title of the book. + /// The name of the author of the book, or for no contributor. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a completed consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: 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; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs new file mode 100644 index 00000000..265d5079 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserMostConsumedEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetUserMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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"); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a track of , together with its artist and album. + /// + /// The Id of the library that owns the track. + /// The title of the track. + /// The title of the album that contains the track. + /// The name of the artist of the album. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false)); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a book of , together with an author contributor when a name is supplied. + /// + /// The Id of the library that owns the book. + /// The title of the book. + /// The name of the author of the book, or for no contributor. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a completed consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: 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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..85fb9421 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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"); + } + + /// + /// Seeds two libraries owned by , a track with three sessions, and a book with one session. + /// + /// The Id of the user that owns the libraries and the consumption records. + /// The Ids of the music library, the track, the ebook library, and the book, and the unique name of the book author. + 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); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a track of , together with its artist and album. + /// + /// The Id of the library that owns the track. + /// The title of the track. + /// The title of the album that contains the track. + /// The name of the artist of the album. + /// The tag names carried by the track. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList tagNames) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false)); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false); + foreach (string tagName in tagNames) + track.Tags.Add(_tagEntityFixture.Create(name: tagName)); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a book of , together with an author contributor when a name is supplied. + /// + /// The Id of the library that owns the book. + /// The title of the book. + /// The name of the author of the book, or for no contributor. + /// The tag names carried by the book. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null, IReadOnlyList? tagNames = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The date and time when the session started. + /// The date and time when the session last received activity. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + DateTime startedOnUtc, + DateTime lastActivityOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: startedOnUtc, + lastActivityOnUtc: 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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..f0f30f79 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRecentlyConsumedEndpointTests : IClassFixture, 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(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetUserRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? meHistory = await DeserializeAsync>(meResponse); + PaginatedResponse? userHistory = await DeserializeAsync>(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? history = await DeserializeAsync>(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? history = await DeserializeAsync>(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"); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a track of , together with its artist and album. + /// + /// The Id of the library that owns the track. + /// The title of the track. + /// The title of the album that contains the track. + /// The name of the artist of the album. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false)); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a book of , together with an author contributor when a name is supplied. + /// + /// The Id of the library that owns the book. + /// The title of the book. + /// The name of the author of the book, or for no contributor. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Seeds a completed consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: 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; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..4485ba4d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointTests : IClassFixture, IAsyncLifetime +{ + private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc); + private static readonly DateTime s_trackStoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc); + private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc); + private static readonly DateTime s_uncountedBookStartedOnUtc = new(2026, 2, 5, 10, 0, 0, DateTimeKind.Utc); + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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"); + } + + /// + /// 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. + /// + /// The Id of the user that owns the libraries and the consumption records. + /// + /// The Ids of the music library and the ebook library, and the unique favourite, book club, rock, and ignored tag names that were seeded. + /// + 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(); + + // 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 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); + } + + /// + /// Seeds a consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The state of the session. + /// The date and time when the session started. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + ConsumptionStatus status, + DateTime startedOnUtc, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: status, + startedOnUtc: startedOnUtc, + lastActivityOnUtc: startedOnUtc.AddMinutes(1), + endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2), + consumedDurationMilliseconds: consumedDurationMilliseconds, + lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset, + lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0, + lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null, + lastProgressFraction: 0, + consecutivePagesRead: consecutivePagesRead); + dbContext.MediaConsumptionRecords.Add(record); + await dbContext.SaveChangesAsync(); + return recordId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..98fc0281 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs @@ -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; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserTagConsumptionEndpointTests : IClassFixture, IAsyncLifetime +{ + private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc); + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetUserTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + 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? tags = await DeserializeAsync>(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? tags = await DeserializeAsync>(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"); + } + + /// + /// Seeds a media library type owned by . + /// + /// The Id of the user that owns the library. + /// The type of the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a tagged track of , together with its artist and album. + /// + /// The Id of the library that owns the track. + /// The title of the track. + /// The title of the album that contains the track. + /// The name of the artist of the album. + /// The tag names carried by the track. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList tagNames) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false)); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false)); + TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false); + foreach (string tagName in tagNames) + track.Tags.Add(_tagEntityFixture.Create(name: tagName)); + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a tagged book of . + /// + /// The Id of the library that owns the book. + /// The title of the book. + /// The tag names carried by the book. + /// The Id of the seeded book. + private async Task SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList tagNames) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid bookId = Guid.NewGuid(); + BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false); + foreach (string tagName in tagNames) + book.Tags.Add(_tagEntityFixture.Create(name: tagName)); + dbContext.Books.Add(book); + await dbContext.SaveChangesAsync(); + return bookId; + } + + /// + /// Seeds a completed consumption record of a media item for . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the media item. + /// The kind of the consumed media item. + /// The Id of the consumed media item. + /// The active duration consumed by the session, in milliseconds. + /// The number of consecutive pages read in the session. + /// The Id of the seeded record. + private async Task SeedRecordAsync( + Guid userId, + Guid libraryId, + MediaKind mediaKind, + Guid mediaItemId, + long consumedDurationMilliseconds, + int consecutivePagesRead) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: mediaKind, + mediaItemId: mediaItemId, + status: ConsumptionStatus.Completed, + startedOnUtc: s_startedOnUtc, + lastActivityOnUtc: s_startedOnUtc.AddMinutes(1), + endedOnUtc: s_startedOnUtc.AddMinutes(2), + consumedDurationMilliseconds: consumedDurationMilliseconds, + lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset, + lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0, + lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null, + lastProgressFraction: 0, + consecutivePagesRead: consecutivePagesRead); + dbContext.MediaConsumptionRecords.Add(record); + await dbContext.SaveChangesAsync(); + return recordId; + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id. + /// + /// The username of the seeded user. + /// The Id of the seeded user. + private async Task SeedUserAsync(string username) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return userId; + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues)); + string cacheControl = string.Join(", ", cacheControlValues!); + Assert.Contains("private", cacheControl); + Assert.Contains("no-store", cacheControl); + Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues)); + Assert.Contains("Authorization", varyValues!); + } + + /// + /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The validation error codes that must all be present. + private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + string[] expectedValidationErrors = [.. expectedErrorCodes.Order()]; + string[] actualValidationErrors = [.. errors["General.Validation"].Order()]; + Assert.Equal(expectedValidationErrors, actualValidationErrors); + } + + /// + /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Asserts that the response is an unauthorized problem details carrying the expected request instance path. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..f6a2eda5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearConsumptionHistoryEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/consumption-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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..4b014d20 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserConsumptionHistoryEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/consumption-history"; + + 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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + await AssertRecordsArePreservedAsync(otherUserRecordId); + } + + [Fact] + public async Task 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("")] // 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent in. + /// The validation error code expected when the value reaches the validator. + private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode) + { + string content = await response.Content.ReadAsStringAsync(); + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + + if (response.StatusCode == HttpStatusCode.UnprocessableEntity) + { + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload still in place, independent of how the server escapes it. + string escapedPayload = Uri.EscapeDataString(payload); + int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal); + string? instance = problemDetails["instance"].GetString(); + Assert.NotNull(instance); + Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path."); + Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal); + Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + } + 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); + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs new file mode 100644 index 00000000..43ec3dca --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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("")] // 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that a malicious query value is rejected with the exact RFC 4918 validation problem shape. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent on. + /// The validation error code expected when the value reaches the validator. + 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(requestPath, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + + AssertNoSensitiveData(content); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + } + + /// + /// Asserts that the resume points identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be deleted. + private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs new file mode 100644 index 00000000..165515b4 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserResumePointsEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + await 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("")] // 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("")] // 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent in. + /// The validation error code expected when the value reaches the validator. + private async Task 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload still in place, independent of how the server escapes it. + string escapedPayload = Uri.EscapeDataString(payload); + int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal); + string? instance = problemDetails["instance"].GetString(); + Assert.NotNull(instance); + Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path."); + Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal); + Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + } + 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); + } + + /// + /// Asserts that a malicious query value is rejected with the exact RFC 4918 validation problem shape. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent on. + /// The validation error code expected when the value reaches the validator. + 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(requestPath, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + + AssertNoSensitiveData(content); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + } + + /// + /// Asserts that the resume points identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be deleted. + private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..bf9a2c84 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionRecordEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + + private static readonly DateTime s_startedOnUtc = new(2026, 5, 1, 9, 0, 0, DateTimeKind.Utc); + private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 1, 9, 10, 0, DateTimeKind.Utc); + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new(); + private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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("")] // 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent in. + /// The validation error code expected when the value reaches the validator. + private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode) + { + string content = await response.Content.ReadAsStringAsync(); + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + + if (response.StatusCode == HttpStatusCode.UnprocessableEntity) + { + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload still in place, independent of how the server escapes it. + string escapedPayload = Uri.EscapeDataString(payload); + int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal); + string? instance = problemDetails["instance"].GetString(); + Assert.NotNull(instance); + Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path."); + Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal); + Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + } + 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); + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..249158ca --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteUserConsumptionRecordEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + + private static readonly DateTime s_startedOnUtc = new(2026, 5, 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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + await AssertRecordsArePreservedAsync(otherUserRecordId); + } + + [Fact] + public async Task 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("")] // 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("")] // 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by . + /// + /// The Id of the user that owns the library. + /// The title of the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100)); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a consumption record of a music track of . + /// + /// The Id of the user that owns the record. + /// The Id of the library that contains the consumed track. + /// The Id of the seeded consumption record. + private async Task SeedRecordAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid recordId = Guid.NewGuid(); + dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create( + id: recordId, + userId: userId, + libraryId: libraryId, + mediaKind: MediaKind.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; + } + + /// + /// Seeds a resume point of . + /// + /// The Id of the user that owns the resume point. + /// The Id of the library that contains the media item. + /// The Id of the seeded resume point. + private async Task SeedResumePointAsync(Guid userId, Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path the value was sent in. + /// The validation error code expected when the value reaches the validator. + private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode) + { + string content = await response.Content.ReadAsStringAsync(); + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + + if (response.StatusCode == HttpStatusCode.UnprocessableEntity) + { + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload still in place, independent of how the server escapes it. + string escapedPayload = Uri.EscapeDataString(payload); + int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal); + string? instance = problemDetails["instance"].GetString(); + Assert.NotNull(instance); + Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path."); + Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal); + Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + } + 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); + } + + /// + /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be deleted. + private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion + // has run, instead of assuming that it already has. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + if (storedRecords.Count == 0) + return; + await Task.Delay(100); + } + Assert.Empty(storedRecords); + } + + /// + /// Asserts that the consumption records identified by are still stored once the request transaction has completed. + /// + /// The Ids of the consumption records that must be preserved. + private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedRecords = []; + // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that + // completion has run, instead of trusting the state observed right after the response. + for (int attempt = 0; attempt < 20; attempt++) + { + storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking() + .Where(record => recordIds.Contains(record.Id)) + .ToListAsync(); + Assert.Equal(recordIds.Length, storedRecords.Count); + await Task.Delay(100); + } + Assert.Equal(recordIds.Length, storedRecords.Count); + } + + /// + /// Asserts that the resume points identified by are still stored once the request transaction has completed. + /// + /// The Ids of the resume points that must be preserved. + private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List 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); + } + + /// + /// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..f9cb0a45 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture, 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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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(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("")] // 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(); + 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(); + } + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and one completed consumption session of one of its tracks. + /// + /// The Id of the user that owns the records. + /// The Id of the seeded library. + private async Task SeedCompletedMusicSessionAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"users\"", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"total\"", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized statistics expose only the fields of their documented response contract. + /// + /// The response body to assert on. + 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); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..86ab703c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/consumption-statistics"; + + 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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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(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(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("")] // 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(); + Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId)); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection + [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + public async Task 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and one completed consumption session of one of its tracks. + /// + /// The Id of the user that owns the records. + /// The Id of the seeded library. + private async Task SeedCompletedMusicSessionAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"mediaKindSummaries\"", content, StringComparison.Ordinal); + Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized statistics expose only the fields of their documented response contract. + /// + /// The response body to assert on. + 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); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..6b83979f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserConsumptionStatisticsEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/consumption-statistics"; + + 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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + } + + [Fact] + public async Task 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(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(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and one completed consumption session of one of its tracks. + /// + /// The Id of the user that owns the records. + /// The Id of the seeded library. + private async Task SeedCompletedMusicSessionAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path that precedes the malicious value. + /// The request path that follows the malicious value. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload 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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"mediaKindSummaries\"", content, StringComparison.Ordinal); + Assert.DoesNotContain("\"countedSessionCount\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized statistics expose only the fields of their documented response contract. + /// + /// The response body to assert on. + 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); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs new file mode 100644 index 00000000..505df6e2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/consumption-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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? history = JsonSerializer.Deserialize>(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? history = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and two completed consumption sessions of one of its tracks. + /// + /// The Id of the user that owns the history. + /// The title of the consumed track. + /// The Ids of the seeded library and of the consumed media item. + private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized consumed items expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs new file mode 100644 index 00000000..8ff6547c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserMostConsumedEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/consumption-history/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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + } + + [Fact] + public async Task 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? history = JsonSerializer.Deserialize>(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? history = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and two completed consumption sessions of one of its tracks. + /// + /// The Id of the user that owns the history. + /// The title of the consumed track. + /// The Ids of the seeded library and of the consumed media item. + private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path that precedes the malicious value. + /// The request path that follows the malicious value. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload 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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized consumed items expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..7801035d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/consumption-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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? history = JsonSerializer.Deserialize>(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? history = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and a completed consumption session of one of its tracks. + /// + /// The Id of the user that owns the history. + /// The title of the consumed track. + /// The Ids of the seeded library and of the consumed media item. + private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized consumed items expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..5fed89c5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRecentlyConsumedEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/consumption-history/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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + } + + [Fact] + public async Task 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? history = JsonSerializer.Deserialize>(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? history = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and a completed consumption session of one of its tracks. + /// + /// The Id of the user that owns the history. + /// The title of the consumed track. + /// The Ids of the seeded library and of the consumed media item. + private async Task<(Guid LibraryId, Guid MediaItemId)> SeedConsumedTrackAsync(Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path that precedes the malicious value. + /// The request path that follows the malicious value. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload 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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"data\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized consumed items expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..e1e23995 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/consumption-statistics/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 _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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? tags = JsonSerializer.Deserialize>(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? tags = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a uniquely tagged track in a library owned by and one completed session of it. + /// + /// The Id of the user that owns the records. + /// The unique name of the seeded tag. + private async Task SeedTaggedConsumptionAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized tags expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..f1ada4f3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs @@ -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; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserTagConsumptionEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH_PREFIX = "/api/v1/users/"; + private const string PATH_SUFFIX = "/consumption-statistics/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 _seededUsernames = []; + private readonly List _adminUserIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + 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 foreignProblem = await ReadProblemDetailsAsync(foreignResponse); + Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse); + Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32()); + Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString()); + Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString()); + Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString()); + } + + [Fact] + public async Task 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? tags = JsonSerializer.Deserialize>(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? tags = JsonSerializer.Deserialize>(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("")] // 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(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a user distinct from the authenticated test user and returns its Id and username. + /// + /// The Id and username of the seeded user. + private async Task<(Guid UserId, string Username)> SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"); + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a uniquely tagged track in a library owned by and one completed session of it. + /// + /// The Id of the user that owns the records. + /// The unique name of the seeded tag. + private async Task SeedTaggedConsumptionAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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; + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is the exact not authorized problem document and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Reads the problem details document of . + /// + /// The HTTP response to read. + /// The parsed problem details fields. + private async Task> ReadProblemDetailsAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + return problemDetails!; + } + + /// + /// Asserts that a malicious route value is rejected without disclosing internals. + /// + /// The HTTP response to assert on. + /// The malicious value that was sent. + /// The request path that precedes the malicious value. + /// The request path that follows the malicious value. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task 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? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + // The instance is the request path with the rejected payload 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? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains(expectedErrorCode, errors["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors!.Keys); + Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]); + + AssertNonCacheable(response); + AssertNoSensitiveData(content); + Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the serialized tags expose only the fields of their documented response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the test users and admin users created by the test. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + foreach (Guid userId in _adminUserIds) + _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/ClearResumePointsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/ClearResumePointsRequestMappingTests.cs new file mode 100644 index 00000000..933c44bb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/ClearResumePointsRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsRequestMappingTests +{ + private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMappingTests.cs new file mode 100644 index 00000000..5992d7dd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetAllUsersConsumptionStatisticsRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsRequestMappingTests +{ + private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMappingTests.cs new file mode 100644 index 00000000..b16e8142 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetConsumptionStatisticsRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsRequestMappingTests +{ + private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetMostConsumedRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetMostConsumedRequestMappingTests.cs new file mode 100644 index 00000000..31f886b7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetMostConsumedRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedRequestMappingTests +{ + private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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(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(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(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(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(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); + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMappingTests.cs new file mode 100644 index 00000000..3700f3be --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedRequestMappingTests +{ + private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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(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(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(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(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(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); + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMappingTests.cs new file mode 100644 index 00000000..bdcc5fd7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionRequestMappingTests +{ + private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs index c0d3c668..b9200372 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs @@ -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 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 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 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().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"); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandlerTests.cs index 0890ce53..7a48ba64 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryHandlerTests.cs @@ -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()); + libraryId, + MediaKind.MusicTrack, + Arg.Is(value => value == new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)), + Arg.Is(value => value == new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc)), + Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidatorTests.cs index 697137cb..b4db7bb4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsQueryValidatorTests.cs @@ -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 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 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 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 result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandlerTests.cs index d207b11a..5e21d97a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryHandlerTests.cs @@ -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(), null, mediaKind, fromUtc, toUtc, Arg.Any()); + Arg.Any(), + null, + MediaKind.Book, + Arg.Is(value => value == new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc)), + Arg.Is(value => value == new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc)), + Arg.Any()); } [Fact] diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidatorTests.cs index fbc178aa..a4121212 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetConsumptionStatistics/GetConsumptionStatisticsQueryValidatorTests.cs @@ -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 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 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 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 result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidatorTests.cs index 493dcdc0..dfefa1f6 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidatorTests.cs @@ -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 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 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 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 result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidatorTests.cs index a4c7e31b..bcf67531 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidatorTests.cs @@ -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 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 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 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 result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidatorTests.cs index 1aaa62ee..3a55ef5f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryValidatorTests.cs @@ -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 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 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 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 result = _validator.TestValidate(query); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/ClearResumePointsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/ClearResumePointsRequestTests.cs new file mode 100644 index 00000000..fd3372f3 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/ClearResumePointsRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsRequestTests +{ + private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestTests.cs new file mode 100644 index 00000000..8c974166 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetAllUsersConsumptionStatisticsRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsRequestTests +{ + private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetConsumptionStatisticsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetConsumptionStatisticsRequestTests.cs new file mode 100644 index 00000000..5af809a7 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetConsumptionStatisticsRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsRequestTests +{ + private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetMostConsumedRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetMostConsumedRequestTests.cs new file mode 100644 index 00000000..46466134 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetMostConsumedRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedRequestTests +{ + private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetRecentlyConsumedRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetRecentlyConsumedRequestTests.cs new file mode 100644 index 00000000..84879533 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetRecentlyConsumedRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedRequestTests +{ + private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetTagConsumptionRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetTagConsumptionRequestTests.cs new file mode 100644 index 00000000..cd497b45 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaConsumption/GetTagConsumptionRequestTests.cs @@ -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; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionRequestTests +{ + private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture; + + /// + /// Initializes a new instance of the class. + /// + 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); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..3118fe0f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearConsumptionHistoryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ClearConsumptionHistoryEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public ClearConsumptionHistoryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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(), Arg.Any()) + .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 expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + 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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendClearConsumptionHistoryCommandWithNullTargetUserId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.TargetUserId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs new file mode 100644 index 00000000..c6801ad3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearUserConsumptionHistoryEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserConsumptionHistoryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ClearUserConsumptionHistoryEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public ClearUserConsumptionHistoryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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(), Arg.Any()) + .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 expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + 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(), Arg.Any()) + .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(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendClearConsumptionHistoryCommandWithRouteUserId() + { + // Arrange + Guid userId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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(command => command.TargetUserId == userId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullTargetUserId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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(command => command.TargetUserId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs new file mode 100644 index 00000000..6e7b9d00 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearResumePointsEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ClearResumePointsEndpoint _sut; + private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ClearResumePointsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .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(), Arg.Any()) + .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 expectedErrors = [DomainErrors.Library.LibraryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + 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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendClearResumePointsCommandWithMappedRequestAndNullTargetUserId() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(libraryId: libraryId); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(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 operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs new file mode 100644 index 00000000..50914f68 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearUserResumePointsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ClearUserResumePointsEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ClearUserResumePointsEndpoint _sut; + private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ClearUserResumePointsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .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(), Arg.Any()) + .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 expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.Library.LibraryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "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(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_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(), Arg.Any()) + .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(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(), Arg.Any()) + .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(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 operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..82cac80b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteConsumptionRecordEndpointTests.cs @@ -0,0 +1,209 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; +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.DeleteConsumptionRecord; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteConsumptionRecordEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteConsumptionRecordEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteConsumptionRecordEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["recordId"] = 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 = DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["recordId"] = 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 expectedErrors = [DomainErrors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues.Remove("recordId"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "ConsumptionRecordIdCannotBeEmpty" }, 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(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteConsumptionRecordCommandWithRouteRecordIdAndNullTargetUserId() + { + // Arrange + Guid recordId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.ConsumptionRecordId == recordId.ToString() && + command.TargetUserId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullRecordId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("recordId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.ConsumptionRecordId == null && + command.TargetUserId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs new file mode 100644 index 00000000..c8a73bf2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/DeleteConsumptionRecord/DeleteUserConsumptionRecordEndpointTests.cs @@ -0,0 +1,219 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord; +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.DeleteConsumptionRecord; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteUserConsumptionRecordEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteUserConsumptionRecordEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeleteUserConsumptionRecordEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = 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(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = 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 expectedErrors = [DomainErrors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty, DomainErrors.MediaConsumption.TargetUserIdIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + _sut.HttpContext.Request.RouteValues.Remove("recordId"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "ConsumptionRecordIdCannotBeEmpty", "TargetUserIdIsInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteConsumptionRecordCommandWithRouteValues() + { + // Arrange + Guid userId = Guid.NewGuid(); + Guid recordId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues["userId"] = userId.ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString(); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.ConsumptionRecordId == recordId.ToString() && + command.TargetUserId == userId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullIdentifiers() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + _sut.HttpContext.Request.RouteValues.Remove("userId"); + _sut.HttpContext.Request.RouteValues.Remove("recordId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.ConsumptionRecordId == null && + command.TargetUserId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..188f1192 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs @@ -0,0 +1,232 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics; +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.GetAllUsersConsumptionStatistics; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetAllUsersConsumptionStatisticsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetAllUsersConsumptionStatisticsEndpoint _sut; + private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new(); + private readonly AllUsersConsumptionStatisticsResponseFixture _allUsersConsumptionStatisticsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetAllUsersConsumptionStatisticsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAllUsersConsumptionStatisticsResponse() + { + // Arrange + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + AllUsersConsumptionStatisticsResponse expectedResponse = _allUsersConsumptionStatisticsResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_allUsersConsumptionStatisticsResponseFixture.Create())); + + // 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 + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid, DomainErrors.Library.LibraryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "ConsumptionDateRangeIsInvalid", "LibraryIdCannotBeEmpty" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetAllUsersConsumptionStatisticsQueryWithMappedRequest() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Movie), + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_allUsersConsumptionStatisticsResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Movie) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenOptionalFiltersAreNotProvided_ShouldSendQueryWithNullValues() + { + // Arrange + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create( + includeLibraryId: false, + includeMediaKind: false, + includeFromUtc: false, + includeToUtc: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_allUsersConsumptionStatisticsResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.MediaKind == null && + query.FromUtc == null && + query.ToUtc == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_allUsersConsumptionStatisticsResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..82852f4f --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; +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.GetConsumptionStatistics; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetConsumptionStatisticsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetConsumptionStatisticsEndpoint _sut; + private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new(); + private readonly ConsumptionSummaryResponseFixture _consumptionSummaryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetConsumptionStatisticsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionSummaryResponse() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ConsumptionSummaryResponse expectedResponse = _consumptionSummaryResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + + // 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 + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid, DomainErrors.MediaConsumption.UnsupportedMediaKind]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "ConsumptionDateRangeIsInvalid", "UnsupportedMediaKind" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetConsumptionStatisticsQueryWithMappedRequestAndNullTargetUserId() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Audiobook), + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Audiobook) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenOptionalFiltersAreNotProvided_ShouldSendQueryWithNullValues() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create( + includeLibraryId: false, + includeMediaKind: false, + includeFromUtc: false, + includeToUtc: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == null && + query.MediaKind == null && + query.FromUtc == null && + query.ToUtc == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_consumptionSummaryResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs new file mode 100644 index 00000000..f1e58264 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointTests.cs @@ -0,0 +1,239 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics; +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.GetConsumptionStatistics; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserConsumptionStatisticsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetUserConsumptionStatisticsEndpoint _sut; + private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new(); + private readonly ConsumptionSummaryResponseFixture _consumptionSummaryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserConsumptionStatisticsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionSummaryResponse() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ConsumptionSummaryResponse expectedResponse = _consumptionSummaryResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + _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 + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "TargetUserIdIsInvalid", "ConsumptionDateRangeIsInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetConsumptionStatisticsQueryWithRouteUserIdAndMappedRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.TvEpisode), + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues["userId"] = userId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == userId.ToString() && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.TvEpisode) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullTargetUserId() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_consumptionSummaryResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("userId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_consumptionSummaryResponseFixture.Create()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs new file mode 100644 index 00000000..68affe85 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; +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.GetMostConsumed; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetMostConsumedEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetMostConsumedEndpoint _sut; + private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new(); + private readonly ConsumedItemResponseFixture _consumedItemResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetMostConsumedEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedConsumedItemResponses() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = _paginatedResponseFixture.Create( + data: _consumedItemResponseFixture.CreateMany(count: 2), + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.UnsupportedMediaKind, DomainErrors.Library.LibraryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "UnsupportedMediaKind", "LibraryIdCannotBeEmpty" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetMostConsumedQueryWithMappedRequestAndNullTargetUserId() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Movie), + currentPage: 3, + perPage: 25, + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Movie) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc && + query.PaginationData != null && + query.PaginationData.CurrentPage == 3 && + query.PaginationData.PerPage == 25), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPageBoundsAreNotProvided_ShouldSendQueryWithNullPaginationData() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create( + includeCurrentPage: false, + includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany())); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs new file mode 100644 index 00000000..d9c198b0 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetUserMostConsumedEndpointTests.cs @@ -0,0 +1,279 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed; +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.GetMostConsumed; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserMostConsumedEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetUserMostConsumedEndpoint _sut; + private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new(); + private readonly ConsumedItemResponseFixture _consumedItemResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserMostConsumedEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedConsumedItemResponses() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = _paginatedResponseFixture.Create( + data: _consumedItemResponseFixture.CreateMany(count: 2), + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "TargetUserIdIsInvalid", "ConsumptionDateRangeIsInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetMostConsumedQueryWithRouteUserIdAndMappedRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.PodcastEpisode), + currentPage: 3, + perPage: 25, + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = userId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == userId.ToString() && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.PodcastEpisode) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc && + query.PaginationData != null && + query.PaginationData.CurrentPage == 3 && + query.PaginationData.PerPage == 25), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullTargetUserId() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues.Remove("userId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPageBoundsAreNotProvided_ShouldSendQueryWithNullPaginationData() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create( + includeCurrentPage: false, + includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany())); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..b58bc7be --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; +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.GetRecentlyConsumed; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetRecentlyConsumedEndpoint _sut; + private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new(); + private readonly ConsumedItemResponseFixture _consumedItemResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetRecentlyConsumedEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedConsumedItemResponses() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = _paginatedResponseFixture.Create( + data: _consumedItemResponseFixture.CreateMany(count: 2), + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid, DomainErrors.MediaConsumption.TargetUserIdIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "ConsumptionDateRangeIsInvalid", "TargetUserIdIsInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetRecentlyConsumedQueryWithMappedRequestAndNullTargetUserId() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Book), + currentPage: 3, + perPage: 25, + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Book) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc && + query.PaginationData != null && + query.PaginationData.CurrentPage == 3 && + query.PaginationData.PerPage == 25), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPageBoundsAreNotProvided_ShouldSendQueryWithNullPaginationData() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create( + includeCurrentPage: false, + includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany())); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs new file mode 100644 index 00000000..4e807550 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetUserRecentlyConsumedEndpointTests.cs @@ -0,0 +1,278 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Fixtures.Responses.Common; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.Common; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed; +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.GetRecentlyConsumed; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRecentlyConsumedEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetUserRecentlyConsumedEndpoint _sut; + private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new(); + private readonly ConsumedItemResponseFixture _consumedItemResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserRecentlyConsumedEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPaginatedConsumedItemResponses() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PaginatedResponse expectedResponse = _paginatedResponseFixture.Create( + data: _consumedItemResponseFixture.CreateMany(count: 2), + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + Assert.Single(validationProblemDetails.Errors); + Assert.Equal(new[] { "TargetUserIdIsInvalid" }, validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetRecentlyConsumedQueryWithRouteUserIdAndMappedRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Photo), + currentPage: 3, + perPage: 25, + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = userId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == userId.ToString() && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Photo) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc && + query.PaginationData != null && + query.PaginationData.CurrentPage == 3 && + query.PaginationData.PerPage == 25), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullTargetUserId() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues.Remove("userId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.PaginationData != null && + query.PaginationData.CurrentPage == request.CurrentPage && + query.PaginationData.PerPage == request.PerPage), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenPageBoundsAreNotProvided_ShouldSendQueryWithNullPaginationData() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create( + includeCurrentPage: false, + includePerPage: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany()))); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc && + query.PaginationData == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_paginatedResponseFixture.Create(data: _consumedItemResponseFixture.CreateMany())); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..95fa7c99 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; +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.GetTagConsumption; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetTagConsumptionEndpoint _sut; + private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new(); + private readonly TagConsumptionResponseFixture _tagConsumptionResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTagConsumptionEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTagConsumptionResponses() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _tagConsumptionResponseFixture.CreateMany(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid, DomainErrors.MediaConsumption.UnsupportedMediaKind]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "ConsumptionDateRangeIsInvalid", "UnsupportedMediaKind" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetTagConsumptionQueryWithMappedRequestAndNullTargetUserId() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.MusicTrack), + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.MusicTrack) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenOptionalFiltersAreNotProvided_ShouldSendQueryWithNullValues() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create( + includeLibraryId: false, + includeMediaKind: false, + includeFromUtc: false, + includeToUtc: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == null && + query.MediaKind == null && + query.FromUtc == null && + query.ToUtc == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>(_tagConsumptionResponseFixture.CreateMany()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs new file mode 100644 index 00000000..cc3ccbe1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointTests.cs @@ -0,0 +1,239 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption; +using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption; +using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption; +using Lumina.Contracts.Requests.MediaConsumption; +using Lumina.Contracts.Responses.MediaConsumption; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption; +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.GetTagConsumption; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserTagConsumptionEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetUserTagConsumptionEndpoint _sut; + private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new(); + private readonly TagConsumptionResponseFixture _tagConsumptionResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetUserTagConsumptionEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTagConsumptionResponses() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponse = _tagConsumptionResponseFixture.CreateMany(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .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 + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.Library.LibraryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + _sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid"; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "TargetUserIdIsInvalid", "LibraryIdCannotBeEmpty" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = ApplicationErrors.Authorization.NotAuthorized; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetTagConsumptionQueryWithRouteUserIdAndMappedRequest() + { + // Arrange + Guid userId = Guid.NewGuid(); + string libraryId = Guid.NewGuid().ToString(); + string fromUtc = "2026-01-01T00:00:00Z"; + string toUtc = "2026-02-01T00:00:00Z"; + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create( + libraryId: libraryId, + mediaKind: nameof(MediaKind.Video), + fromUtc: fromUtc, + toUtc: toUtc); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + _sut.HttpContext.Request.RouteValues["userId"] = userId.ToString(); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == userId.ToString() && + query.LibraryId == libraryId && + query.MediaKind == nameof(MediaKind.Video) && + query.FromUtc == fromUtc && + query.ToUtc == toUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullTargetUserId() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>(_tagConsumptionResponseFixture.CreateMany())); + _sut.HttpContext.Request.RouteValues.Remove("userId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.TargetUserId == null && + query.LibraryId == request.LibraryId && + query.MediaKind == request.MediaKind && + query.FromUtc == request.FromUtc && + query.ToUtc == request.ToUtc), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>(_tagConsumptionResponseFixture.CreateMany()); + }, callInfo.Arg())); + _sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString(); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +}