mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit c27621818c
This commit is contained in:
1 parent
54b468855a
commit
d8adf3c1b6
22 files changed
+7664
No files matched your search
+23
@@ -106,6 +106,8 @@ public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Res
|
||||
if (saveStaleResumePointDeletionResult.IsFailure &&
|
||||
!saveStaleResumePointDeletionResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
|
||||
return saveStaleResumePointDeletionResult.Errors;
|
||||
// The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request.
|
||||
await CommitResumePointDeletionAsync(saveStaleResumePointDeletionResult, cancellationToken).ConfigureAwait(false);
|
||||
return DomainErrors.MediaConsumption.MediaResumePointNotFound;
|
||||
}
|
||||
|
||||
@@ -127,6 +129,8 @@ public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Res
|
||||
// concurrency conflict is treated as success; any other persistence failure is still returned.
|
||||
if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
|
||||
return saveChangesResult.Errors;
|
||||
// The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request.
|
||||
await CommitResumePointDeletionAsync(saveChangesResult, cancellationToken).ConfigureAwait(false);
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
}
|
||||
}
|
||||
@@ -146,6 +150,8 @@ public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Res
|
||||
// concurrency conflict is treated as success; any other persistence failure is still returned.
|
||||
if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
|
||||
return saveChangesResult.Errors;
|
||||
// The response is a not-found one, which the request pipeline does not commit, so the deletion is committed here to survive the request.
|
||||
await CommitResumePointDeletionAsync(saveChangesResult, cancellationToken).ConfigureAwait(false);
|
||||
return DomainErrors.WrittenContent.BookNotFound;
|
||||
}
|
||||
}
|
||||
@@ -154,4 +160,21 @@ public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Res
|
||||
|
||||
return getResumePointResult.Value.ToDto().ToResponse();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commits the deletion of a stale or orphan resume point, so that the cleanup survives the not-found response of this query.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The request transaction is committed by <see cref="EventualConsistencyMiddleware"/> only when the response is a success, and this query intentionally
|
||||
/// responds with a not-found error after it cleans up, so the deletion is committed here. A failed save has nothing to persist, and a concurrency
|
||||
/// conflict means that the row is already gone, which is the desired outcome. Committing when no transaction is open is a no-op, which keeps the handler usable outside of the HTTP pipeline.
|
||||
/// </remarks>
|
||||
/// <param name="saveChangesResult">The result of saving the resume point deletion.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
private async Task CommitResumePointDeletionAsync(Result<Success> saveChangesResult, CancellationToken cancellationToken)
|
||||
{
|
||||
if (saveChangesResult.IsFailure)
|
||||
return;
|
||||
await _unitOfWork.CommitTransactionAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
#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.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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.MediaConsumption.CompleteConsumption;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.MediaConsumption.CompleteConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="CompleteConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CompleteConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
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 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 BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly CompleteConsumptionRequestFixture _completeConsumptionRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompleteConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CompleteConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordIsInProgress_ShouldCompleteRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid mediaItemId, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0.1, includePosition: false);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 10, includeLocation: false),
|
||||
progressFraction: 0.95,
|
||||
consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.Completed, record.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(90.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.95, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(10.0, record.LastPosition.TimeOffsetSeconds);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.Completed, storedRecord!.Status);
|
||||
Assert.NotNull(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(90_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.95, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedRecord.LastPositionKind);
|
||||
Assert.Equal(10_000, storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenConsecutivePagesReadIsOmitted_ShouldKeepCountStoredByLastReport()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid mediaItemId, Guid recordId) = await SeedBookRecordAsync(userId, consumedDurationMilliseconds: 120_000, lastProgressFraction: 0.4, lastPositionLocation: "page-7", consecutivePagesRead: 7);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.Location), location: "page-9", includeTimeOffsetSeconds: false),
|
||||
progressFraction: 0.45,
|
||||
consumedDurationInSeconds: 150,
|
||||
includeConsecutivePagesRead: false);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(libraryId, record!.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.Completed, record.Status);
|
||||
Assert.Equal(7, record.ConsecutivePagesRead);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal("page-9", record.LastPosition!.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.Completed, storedRecord!.Status);
|
||||
Assert.Equal(7, storedRecord.ConsecutivePagesRead);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordIsAlreadyTerminal_ShouldReturnConsumptionIsAlreadyTerminal()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.Stopped, consumedDurationMilliseconds: 60_000, lastProgressFraction: 0.6, includePosition: false);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 70);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Conflict, "General.Conflict", "ConsumptionIsAlreadyTerminal", url, "https://tools.ietf.org/html/rfc9110#section-15.5.10");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordDoesNotExist_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordBelongsToAnotherUser_ShouldReturnConsumptionRecordNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(otherUserId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 15_000, lastProgressFraction: 0.2, includePosition: false);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenConsumedDurationIsLowerThanStored_ShouldReturnConsumedDurationCannotDecrease()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 100_000, lastProgressFraction: 0.3, includePosition: false);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.4, consumedDurationInSeconds: 50);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ConsumedDurationCannotDecrease", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
string url = "/api/v1/users/me/consumption-records/not-a-guid/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library and a consumption record of a music track for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library and the record.</param>
|
||||
/// <param name="status">The state of the seeded consumption session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="includePosition">Whether the record should carry a known position, or none at all.</param>
|
||||
/// <returns>The Ids of the seeded library, media item and consumption record.</returns>
|
||||
private async Task<(Guid libraryId, Guid mediaItemId, Guid recordId)> SeedMusicTrackRecordAsync(Guid userId, ConsumptionStatus status, long consumedDurationMilliseconds, double lastProgressFraction, bool includePosition)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 5_000,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
includeLastPositionKind: includePosition,
|
||||
includeLastPositionTimeOffsetMilliseconds: includePosition,
|
||||
includeLastPositionLocation: includePosition));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, mediaItemId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library and an in-progress consumption record of a book for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library and the record.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionLocation">The last known reading location of the record.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read stored by the record.</param>
|
||||
/// <returns>The Ids of the seeded library, book and consumption record.</returns>
|
||||
private async Task<(Guid libraryId, Guid mediaItemId, Guid recordId)> SeedBookRecordAsync(Guid userId, long consumedDurationMilliseconds, double lastProgressFraction, string lastPositionLocation, int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: mediaItemId, libraryId: libraryId, path: $"/books/{mediaItemId:N}.epub", title: "Test Book", includeMetadata: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: consecutivePagesRead));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, mediaItemId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
#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.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.MediaConsumption.GetConsumptionRecord;
|
||||
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.MediaConsumption.GetConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionRecordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
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 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 BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenRecordBelongsToCurrentUser_ShouldReturnRecordDetails()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid mediaItemId, Guid recordId) = await SeedBookRecordAsync(userId, consumedDurationMilliseconds: 90_500, lastProgressFraction: 0.42, consecutivePagesRead: 12, lastPositionLocation: "chapter-3");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-records/{recordId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Equal(s_startedOnUtc, record.StartedOnUtc);
|
||||
Assert.Equal(s_lastActivityOnUtc, record.LastActivityOnUtc);
|
||||
Assert.Null(record.EndedOnUtc);
|
||||
Assert.Equal(90.5, record.ConsumedDurationInSeconds);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Null(record.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Equal("chapter-3", record.LastPosition.Location);
|
||||
Assert.Equal(0.42, record.LastProgressFraction);
|
||||
Assert.Equal(12, record.ConsecutivePagesRead);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(_, _, Guid recordId) = await SeedBookRecordAsync(otherUserId, consumedDurationMilliseconds: 30_000, lastProgressFraction: 0.2, consecutivePagesRead: 2, lastPositionLocation: "chapter-1");
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenRecordDoesNotExist_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenRecordIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/me/consumption-records/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book library, a book, and an in-progress consumption record of the book for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library and the record.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the record.</param>
|
||||
/// <param name="lastPositionLocation">The last known reading location of the record.</param>
|
||||
/// <returns>The Ids of the seeded library, book and consumption record.</returns>
|
||||
private async Task<(Guid libraryId, Guid mediaItemId, Guid recordId)> SeedBookRecordAsync(Guid userId, long consumedDurationMilliseconds, double lastProgressFraction, int consecutivePagesRead, string lastPositionLocation)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: mediaItemId, libraryId: libraryId, path: $"/books/{mediaItemId:N}.epub", title: "Test Book", includeMetadata: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: consecutivePagesRead));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, mediaItemId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+497
@@ -0,0 +1,497 @@
|
||||
#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.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.MediaConsumption.GetResumePoint;
|
||||
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.MediaConsumption.GetResumePoint;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetResumePointEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetResumePointEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_lastConsumedOnUtc = new(2026, 2, 28, 18, 30, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetResumePointEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetResumePointEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMusicTrackResumePointExists_ShouldReturnResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, MediaKind.MusicTrack, trackId, MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 125_500, lastPositionLocation: null, lastProgressFraction: 0.42);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{trackId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ResumePointResponse? resumePoint = JsonSerializer.Deserialize<ResumePointResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(resumePoint);
|
||||
Assert.Equal(resumePointId, resumePoint!.Id);
|
||||
Assert.Equal(libraryId, resumePoint.LibraryId);
|
||||
Assert.Equal(trackId, resumePoint.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, resumePoint.MediaKind);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, resumePoint.LastPosition.Kind);
|
||||
Assert.Equal(125.5, resumePoint.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Null(resumePoint.LastPosition.Location);
|
||||
Assert.Equal(0.42, resumePoint.LastProgressFraction);
|
||||
Assert.Equal(s_lastConsumedOnUtc, resumePoint.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenBookResumePointExists_ShouldReturnResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, MediaKind.Book, bookId, MediaPositionKind.Location, lastPositionTimeOffsetMilliseconds: null, lastPositionLocation: "chapter-12", lastProgressFraction: 0.6);
|
||||
string url = $"/api/v1/users/me/media-resume-points/Book/{bookId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ResumePointResponse? resumePoint = JsonSerializer.Deserialize<ResumePointResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(resumePoint);
|
||||
Assert.Equal(resumePointId, resumePoint!.Id);
|
||||
Assert.Equal(libraryId, resumePoint.LibraryId);
|
||||
Assert.Equal(bookId, resumePoint.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, resumePoint.MediaKind);
|
||||
Assert.Equal(MediaPositionKind.Location, resumePoint.LastPosition.Kind);
|
||||
Assert.Null(resumePoint.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Equal("chapter-12", resumePoint.LastPosition.Location);
|
||||
Assert.Equal(0.6, resumePoint.LastProgressFraction);
|
||||
Assert.Equal(s_lastConsumedOnUtc, resumePoint.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenResumePointDoesNotExist_ShouldReturnMediaResumePointNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "MediaResumePointNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenResumePointBelongsToAnotherUser_ShouldReturnMediaResumePointNotFoundAndKeepOtherRow()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid resumePointId = await SeedResumePointAsync(otherUserId, Guid.NewGuid(), MediaKind.MusicTrack, mediaItemId, MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 30_000, lastPositionLocation: null, lastProgressFraction: 0.3);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "MediaResumePointNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.NotNull(dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.Id == resumePointId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMediaKindIsPhoto_ShouldReturnMediaKindCannotResume()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/media-resume-points/Photo/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "MediaKindCannotResume", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMediaKindIsMovie_ShouldReturnUnsupportedMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/media-resume-points/Movie/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMediaKindIsNumeric_ShouldReturnUnsupportedMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/media-resume-points/1/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMusicTrackNoLongerExists_ShouldReturnTrackNotFoundAndDeleteResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 30_000, lastPositionLocation: null, lastProgressFraction: 0.3);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
// The cleanup is committed before the not-found result is returned, so the deletion survives the request even though the response is not
|
||||
// a success response, which the request pipeline would otherwise roll back.
|
||||
await AssertResumePointIsDeletedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenBookNoLongerExists_ShouldReturnBookNotFoundAndDeleteResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryAndBookAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, MediaKind.Book, mediaItemId, MediaPositionKind.Location, lastPositionTimeOffsetMilliseconds: null, lastPositionLocation: "chapter-4", lastProgressFraction: 0.4);
|
||||
string url = $"/api/v1/users/me/media-resume-points/Book/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "BookNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
// The cleanup is committed before the not-found result is returned, so the deletion survives the request even though the response is not
|
||||
// a success response, which the request pipeline would otherwise roll back.
|
||||
await AssertResumePointIsDeletedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenLibraryNoLongerTracksProgress_ShouldReturnMediaResumePointNotFoundAndDeleteResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 30_000, lastPositionLocation: null, lastProgressFraction: 0.3);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "MediaResumePointNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
// The cleanup is committed before the not-found result is returned, so the deletion survives the request even though the response is not
|
||||
// a success response, which the request pipeline would otherwise roll back.
|
||||
await AssertResumePointIsDeletedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenMediaItemIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/me/media-resume-points/MusicTrack/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "MediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <returns>The Ids of the seeded library and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, bool shouldTrackConsumptionProgress)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: shouldTrackConsumptionProgress, completionThresholdPercentage: shouldTrackConsumptionProgress ? 100 : null));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/> and a book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, bool shouldTrackConsumptionProgress)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: shouldTrackConsumptionProgress, completionThresholdPercentage: shouldTrackConsumptionProgress ? 100 : null));
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of the provided media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of media that is resumed.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <param name="lastPositionKind">The kind of the position at which the media item can be resumed.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The position at which the media item can be resumed, in milliseconds, when it is a time offset.</param>
|
||||
/// <param name="lastPositionLocation">The locator at which the media item can be resumed, when it is not a time offset.</param>
|
||||
/// <param name="lastProgressFraction">The progress fraction at which the media item can be resumed.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
MediaPositionKind lastPositionKind,
|
||||
long? lastPositionTimeOffsetMilliseconds,
|
||||
string? lastPositionLocation,
|
||||
double lastProgressFraction)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
lastConsumedOnUtc: s_lastConsumedOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume point identified by <paramref name="resumePointId"/> is no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointId">The Id of the resume point that must be deleted.</param>
|
||||
private async Task AssertResumePointIsDeletedAsync(Guid resumePointId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaResumePointEntity? resumePoint = null;
|
||||
// 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++)
|
||||
{
|
||||
resumePoint = dbContext.MediaResumePoints.AsNoTracking().FirstOrDefault(candidate => candidate.Id == resumePointId);
|
||||
if (resumePoint is null)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Null(resumePoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
#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.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.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.MediaConsumption.ReportConsumptionProgress;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.MediaConsumption.ReportConsumptionProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ReportConsumptionProgressEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReportConsumptionProgressEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
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 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 BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly ReportConsumptionProgressRequestFixture _reportConsumptionProgressRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportConsumptionProgressEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ReportConsumptionProgressEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordIsInProgress_ShouldUpdateProgress()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid mediaItemId, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0.1, lastPositionKind: MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 5_000);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 12.5, includeLocation: false),
|
||||
progressFraction: 0.35,
|
||||
consumedDurationInSeconds: 45);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Null(record.EndedOnUtc);
|
||||
Assert.Equal(45.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.35, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(12.5, record.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Null(record.LastPosition.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(45_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.35, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedRecord.LastPositionKind);
|
||||
Assert.Equal(12_500, storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenBookRecordAndLocationPosition_ShouldStoreLocation()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid mediaItemId, Guid recordId) = await SeedBookRecordAsync(userId, consumedDurationMilliseconds: 0, lastProgressFraction: 0.2, lastPositionLocation: "chapter-1");
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.Location), location: "chapter-2", includeTimeOffsetSeconds: false),
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 60);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(libraryId, record!.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Equal(60.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.5, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Null(record.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Equal("chapter-2", record.LastPosition.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(MediaPositionKind.Location, storedRecord!.LastPositionKind);
|
||||
Assert.Equal("chapter-2", storedRecord.LastPositionLocation);
|
||||
Assert.Null(storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordIsCompleted_ShouldReturnConsumptionIsNotInProgress()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.Completed, consumedDurationMilliseconds: 60_000, lastProgressFraction: 1);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.9, consumedDurationInSeconds: 70);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Conflict, "General.Conflict", "ConsumptionIsNotInProgress", url, "https://tools.ietf.org/html/rfc9110#section-15.5.10");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordDoesNotExist_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordBelongsToAnotherUser_ShouldReturnConsumptionRecordNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(otherUserId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 15_000, lastProgressFraction: 0.2, lastPositionKind: MediaPositionKind.TimeOffset, lastPositionTimeOffsetMilliseconds: 15_000);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 90, includeLocation: false),
|
||||
progressFraction: 0.9,
|
||||
consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(s_lastActivityOnUtc, storedRecord.LastActivityOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenConsecutivePagesReadIsPositiveForNonBook_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0.1);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.2, consumedDurationInSeconds: 30, consecutivePagesRead: 3);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ConsecutivePagesReadIsOnlySupportedForPageBasedMedia", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenProgressFractionIsOutOfRange_ShouldReturnInvalidProgressFraction()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0.1);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 1.5, consumedDurationInSeconds: 30);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "InvalidProgressFraction");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenConsumedDurationIsLowerThanStored_ShouldReturnConsumedDurationCannotDecrease()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid recordId) = await SeedMusicTrackRecordAsync(userId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 100_000, lastProgressFraction: 0.3);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.4, consumedDurationInSeconds: 50);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ConsumedDurationCannotDecrease", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = "/api/v1/users/me/consumption-records/not-a-guid/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library and an in-progress consumption record of a music track for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library and the record.</param>
|
||||
/// <param name="status">The state of the seeded consumption session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionKind">The kind of the last known position, or <see langword="null"/> when the record has no known position.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The last known position, in milliseconds, when it is a time offset.</param>
|
||||
/// <returns>The Ids of the seeded library, media item and consumption record.</returns>
|
||||
private async Task<(Guid libraryId, Guid mediaItemId, Guid recordId)> SeedMusicTrackRecordAsync(
|
||||
Guid userId,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
double lastProgressFraction,
|
||||
MediaPositionKind? lastPositionKind = null,
|
||||
long? lastPositionTimeOffsetMilliseconds = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
includeLastPositionKind: lastPositionKind.HasValue,
|
||||
includeLastPositionTimeOffsetMilliseconds: lastPositionKind.HasValue,
|
||||
includeLastPositionLocation: lastPositionKind.HasValue));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, mediaItemId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library and an in-progress consumption record of a book for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library and the record.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionLocation">The last known reading location of the record.</param>
|
||||
/// <returns>The Ids of the seeded library, book and consumption record.</returns>
|
||||
private async Task<(Guid libraryId, Guid mediaItemId, Guid recordId)> SeedBookRecordAsync(Guid userId, long consumedDurationMilliseconds, double lastProgressFraction, string lastPositionLocation)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: []));
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: mediaItemId, libraryId: libraryId, path: $"/books/{mediaItemId:N}.epub", title: "Test Book", includeMetadata: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.InProgress,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 5));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, mediaItemId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
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.MediaConsumption.StartConsumption;
|
||||
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;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.MediaConsumption.StartConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StartConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_lastConsumedOnUtc = new(2026, 2, 28, 18, 30, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public StartConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryAndTrackExist_ShouldCreateInProgressRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/MusicTrack/{trackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.NotEqual(Guid.Empty, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(trackId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Null(record.EndedOnUtc);
|
||||
Assert.Equal(0.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Null(record.LastPosition);
|
||||
Assert.Equal(0.0, record.LastProgressFraction);
|
||||
Assert.Equal(0, record.ConsecutivePagesRead);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == record.Id);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(userId, storedRecord!.UserId);
|
||||
Assert.Equal(libraryId, storedRecord.LibraryId);
|
||||
Assert.Equal(trackId, storedRecord.MediaItemId);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryAndBookExist_ShouldCreateInProgressRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/Book/{bookId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.NotEqual(Guid.Empty, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(bookId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Null(record.EndedOnUtc);
|
||||
Assert.Equal(0.0, record.ConsumedDurationInSeconds);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == record.Id);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(userId, storedRecord!.UserId);
|
||||
Assert.Equal(MediaKind.Book, storedRecord.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenResumePointExists_ShouldContinueFromStoredPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
await SeedResumePointAsync(userId, libraryId, bookId, lastPositionLocation: "chapter-4", lastProgressFraction: 0.6);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/Book/{bookId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(libraryId, record!.LibraryId);
|
||||
Assert.Equal(bookId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.Book, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Null(record.EndedOnUtc);
|
||||
Assert.Equal(0.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.6, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Equal("chapter-4", record.LastPosition.Location);
|
||||
Assert.Null(record.LastPosition.TimeOffsetSeconds);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == record.Id);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(MediaPositionKind.Location, storedRecord!.LastPositionKind);
|
||||
Assert.Equal("chapter-4", storedRecord.LastPositionLocation);
|
||||
Assert.Equal(0.6, storedRecord.LastProgressFraction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFound()
|
||||
{
|
||||
// Arrange
|
||||
// Only an admin can reach the library lookup for a library that is not owned by the caller, so the admin role is granted to the
|
||||
// authenticated test user to exercise the missing library branch instead of the ownership branch that precedes it.
|
||||
Guid userId = GetCurrentUserId();
|
||||
await GrantAdminRoleAsync(userId);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "LibraryNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenTrackDoesNotExist_ShouldReturnTrackNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenBookDoesNotExist_ShouldReturnBookNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryAndBookAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/Book/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "BookNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenTrackBelongsToAnotherLibrary_ShouldReturnTrackNotFound()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
(_, Guid otherLibraryTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/MusicTrack/{otherLibraryTrackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/media-items/MusicTrack/{otherTrackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenMediaKindIsPhoto_ShouldReturnUnsupportedMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid libraryId, _) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: false);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/Photo/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenMediaKindIsNumeric_ShouldReturnUnsupportedMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
// The numeric route value parses to MusicTrack as an enumeration value, but only the member names are accepted as a media kind.
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/1/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/not-a-guid/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenMediaItemIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/MusicTrack/not-a-guid/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "MediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <returns>The Ids of the seeded library and track.</returns>
|
||||
private async Task<(Guid libraryId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, bool shouldTrackConsumptionProgress)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: shouldTrackConsumptionProgress, completionThresholdPercentage: shouldTrackConsumptionProgress ? 100 : null));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds an ebook library owned by <paramref name="userId"/> and a book belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <returns>The Ids of the seeded library and book.</returns>
|
||||
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId, bool shouldTrackConsumptionProgress)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: shouldTrackConsumptionProgress, completionThresholdPercentage: shouldTrackConsumptionProgress ? 100 : null));
|
||||
dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, bookId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of a book for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the book.</param>
|
||||
/// <param name="mediaItemId">The Id of the book to resume.</param>
|
||||
/// <param name="lastPositionLocation">The reading location at which the book can be resumed.</param>
|
||||
/// <param name="lastProgressFraction">The progress fraction at which the book can be resumed.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId, string lastPositionLocation, double lastProgressFraction)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.Location,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
lastConsumedOnUtc: s_lastConsumedOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grants the admin role to the user identified by <paramref name="userId"/>, so that the library ownership policy allows access to any library.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that receives the admin role.</param>
|
||||
private async Task GrantAdminRoleAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService<IDataSeedService>();
|
||||
await dataSeedService.SetDefaultAuthorizationRolesAsync(userId, CancellationToken.None);
|
||||
await dataSeedService.SetAdminRoleToAdministratorAccount(userId, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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.MediaConsumption.StopConsumption;
|
||||
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.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.MediaConsumption.StopConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StopConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
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 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 MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly StopConsumptionRequestFixture _stopConsumptionRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public StopConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenProgressIsBelowCompletionThreshold_ShouldStopRecordAndCreateResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId, mediaItemId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0, includePosition: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 30, includeLocation: false),
|
||||
progressFraction: 0.3,
|
||||
consumedDurationInSeconds: 60);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(mediaItemId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.Stopped, record.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(60.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.3, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(30.0, record.LastPosition.TimeOffsetSeconds);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.Stopped, storedRecord!.Status);
|
||||
Assert.NotNull(storedRecord.EndedOnUtc);
|
||||
MediaResumePointEntity? resumePoint = dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.UserId == userId && candidate.MediaKind == MediaKind.MusicTrack && candidate.MediaItemId == mediaItemId);
|
||||
Assert.NotNull(resumePoint);
|
||||
Assert.Equal(libraryId, resumePoint!.LibraryId);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, resumePoint.LastPositionKind);
|
||||
Assert.Equal(30_000, resumePoint.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal(0.3, resumePoint.LastProgressFraction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenProgressReachesCompletionThreshold_ShouldCompleteRecordAndDeleteResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 90);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId, mediaItemId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0, includePosition: false);
|
||||
await SeedResumePointAsync(userId, libraryId, mediaItemId, lastPositionTimeOffsetMilliseconds: 15_000, lastProgressFraction: 0.5);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 40, includeLocation: false),
|
||||
progressFraction: 0.9,
|
||||
consumedDurationInSeconds: 100);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(ConsumptionStatus.Completed, record.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(0.9, record.LastProgressFraction);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.Completed, storedRecord!.Status);
|
||||
Assert.NotNull(storedRecord.EndedOnUtc);
|
||||
Assert.Null(dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.UserId == userId && candidate.MediaKind == MediaKind.MusicTrack && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenLibraryDoesNotTrackProgress_ShouldStopRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId, mediaItemId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 0, lastProgressFraction: 0, includePosition: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 30, includeLocation: false),
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 60);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(ConsumptionStatus.Stopped, record!.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(1.0, record.LastProgressFraction);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.Null(dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.UserId == userId && candidate.MediaKind == MediaKind.MusicTrack && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenRecordIsAlreadyTerminal_ShouldReturnConsumptionIsAlreadyTerminal()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId, Guid.NewGuid(), status: ConsumptionStatus.Completed, consumedDurationMilliseconds: 60_000, lastProgressFraction: 1, includePosition: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.9, consumedDurationInSeconds: 70);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Conflict, "General.Conflict", "ConsumptionIsAlreadyTerminal", url, "https://tools.ietf.org/html/rfc9110#section-15.5.10");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenRecordDoesNotExist_ShouldReturnConsumptionRecordNotFound()
|
||||
{
|
||||
// Arrange
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenRecordBelongsToAnotherUser_ShouldReturnConsumptionRecordNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid libraryId = await SeedLibraryAsync(otherUserId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100);
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = await SeedRecordAsync(otherUserId, libraryId, mediaItemId, status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 15_000, lastProgressFraction: 0.2, includePosition: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.9, consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", "ConsumptionRecordNotFound", url, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(stored => stored.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
Assert.Null(dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.UserId == otherUserId && candidate.MediaKind == MediaKind.MusicTrack && candidate.MediaItemId == mediaItemId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenConsumedDurationIsLowerThanStored_ShouldReturnConsumedDurationCannotDecrease()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
|
||||
Guid recordId = await SeedRecordAsync(userId, libraryId, Guid.NewGuid(), status: ConsumptionStatus.InProgress, consumedDurationMilliseconds: 100_000, lastProgressFraction: 0.3, includePosition: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.4, consumedDurationInSeconds: 50);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Forbidden", "ConsumedDurationCannotDecrease", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenRecordIdIsNotParseable_ShouldReturnUnprocessableEntity()
|
||||
{
|
||||
// Arrange
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = "/api/v1/users/me/consumption-records/not-a-guid/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> with the provided consumption settings.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <param name="completionThresholdPercentage">The percentage at which a stopped session of the library is considered completed.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, bool shouldTrackConsumptionProgress, int? completionThresholdPercentage)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Music Library",
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [],
|
||||
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
|
||||
completionThresholdPercentage: completionThresholdPercentage));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a music track for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the seeded consumption session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="includePosition">Whether the record should carry a known position, or none at all.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, Guid mediaItemId, ConsumptionStatus status, long consumedDurationMilliseconds, double lastProgressFraction, bool includePosition)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 5_000,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
includeLastPositionKind: includePosition,
|
||||
includeLastPositionTimeOffsetMilliseconds: includePosition,
|
||||
includeLastPositionLocation: includePosition));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of a music track for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The position at which the media item can be resumed, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The progress fraction at which the media item can be resumed.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId, long lastPositionTimeOffsetMilliseconds, double lastProgressFraction)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastProgressFraction: lastProgressFraction));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+516
@@ -0,0 +1,516 @@
|
||||
#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.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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.MediaConsumption.CompleteConsumption;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.MediaConsumption.CompleteConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="CompleteConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CompleteConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const long SEEDED_VERSION = 7;
|
||||
|
||||
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 MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly CompleteConsumptionRequestFixture _completeConsumptionRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompleteConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public CompleteConsumptionEndpointTests(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 CompleteConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/complete";
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.TimeOffset, 5_000, null);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 60, includeLocation: false),
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 120);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(ConsumptionStatus.Completed, record.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(120.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(1.0, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(60.0, record.LastPosition.TimeOffsetSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenRecordDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteConsumption_WhenAnotherUsersRecordIsTargeted_ShouldReturnNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherRecordId) = await SeedRecordAsync(otherUserId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 15_000, 0.2, MediaPositionKind.TimeOffset, 15_000, null);
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 90, includeLocation: false),
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{otherRecordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(record => record.Id == otherRecordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedRecord.LastPositionKind);
|
||||
Assert.Equal(15_000, storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal(SEEDED_VERSION, storedRecord.Version);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task CompleteConsumption_WithSqlInjectionInRecordId_ShouldRejectWithoutLeaking(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(includePosition: false, progressFraction: 1, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Uri.EscapeDataString(maliciousRecordId)}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task CompleteConsumption_WithUnknownPositionKind_ShouldRejectWithoutLeaking(string maliciousPositionKind)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: maliciousPositionKind),
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, url, "InvalidMediaPosition");
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(maliciousPositionKind, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task CompleteConsumption_WithOpaquePositionLocation_ShouldStoreItVerbatimWithoutLeaking(string location)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.Book, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.Location, null, "chapter-1");
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.Location), location: location, includeTimeOffsetSeconds: false),
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 30);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/complete";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(ConsumptionStatus.Completed, record!.Status);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Equal(location, record.LastPosition.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(location, storedRecord!.LastPositionLocation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/> and a consumption record of a media item belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="mediaKind">The kind of media that the record consumes.</param>
|
||||
/// <param name="status">The state of the seeded session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionKind">The kind of the last known position.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The last known position, in milliseconds, when it is a time offset.</param>
|
||||
/// <param name="lastPositionLocation">The last known opaque locator, when it is a location.</param>
|
||||
/// <returns>The Ids of the seeded library and consumption record.</returns>
|
||||
private async Task<(Guid LibraryId, Guid RecordId)> SeedRecordAsync(
|
||||
Guid userId,
|
||||
MediaKind mediaKind,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
double lastProgressFraction,
|
||||
MediaPositionKind lastPositionKind,
|
||||
long? lastPositionTimeOffsetMilliseconds,
|
||||
string? lastPositionLocation)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Media Library",
|
||||
libraryType: mediaKind == MediaKind.Book ? LibraryType.EBook : LibraryType.Music,
|
||||
contentLocations: [],
|
||||
shouldTrackConsumptionProgress: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
version: SEEDED_VERSION));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the standard validation problem of the complete consumption route.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized consumption record exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.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.MediaConsumption.GetConsumptionRecord;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.MediaConsumption.GetConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionRecordEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
private readonly LuminaApiFactory _apiFactory;
|
||||
private readonly HttpClient _client;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionRecordEndpointTests(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 GetConsumptionRecord_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid recordId = await SeedRecordAsync(userId, ConsumptionStatus.InProgress, 15_000, 0.2, 15_000);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}";
|
||||
|
||||
// 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);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(MediaKind.MusicTrack, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Equal(15.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.2, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(15.0, record.LastPosition.TimeOffsetSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenRecordDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WhenAnotherUsersRecordIsRequested_ShouldReturnNotFoundWithoutDisclosingExistence()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherRecordId = await SeedRecordAsync(otherUserId, ConsumptionStatus.InProgress, 42_000, 0.4, 42_000);
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/consumption-records/{otherRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(response);
|
||||
HttpResponseMessage missingResponse = await _client.GetAsync($"/api/v1/users/me/consumption-records/{Guid.NewGuid()}");
|
||||
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode);
|
||||
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());
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(record => record.Id == otherRecordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(otherUserId, storedRecord!.UserId);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord.Status);
|
||||
Assert.Equal(42_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.4, storedRecord.LastProgressFraction);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionRecord_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnOwnRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid ownRecordId = await SeedRecordAsync(userId, ConsumptionStatus.InProgress, 10_000, 0.1, 10_000);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherRecordId = await SeedRecordAsync(otherUserId, ConsumptionStatus.Completed, 90_000, 1.0, 90_000);
|
||||
string url = $"/api/v1/users/me/consumption-records/{ownRecordId}?userId={otherUserId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(ownRecordId, record!.Id);
|
||||
Assert.NotEqual(otherRecordId, record.Id);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == otherRecordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(otherUserId, storedRecord!.UserId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task GetConsumptionRecord_WithSqlInjectionInRecordId_ShouldRejectWithoutLeaking(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Uri.EscapeDataString(maliciousRecordId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/> and a consumption record of a music track belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="status">The state of the seeded session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The last known position, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded consumption record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
double lastProgressFraction,
|
||||
long lastPositionTimeOffsetMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details document of <paramref name="response"/>.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The parsed problem details fields.</returns>
|
||||
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized consumption record exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+543
@@ -0,0 +1,543 @@
|
||||
#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.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.MediaConsumption.GetResumePoint;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.MediaConsumption.GetResumePoint;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetResumePointEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetResumePointEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const long SEEDED_VERSION = 7;
|
||||
|
||||
private static readonly DateTime s_lastConsumedOnUtc = new(2026, 2, 28, 18, 30, 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 MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetResumePointEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetResumePointEndpointTests(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 GetResumePoint_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, trackId, MediaPositionKind.TimeOffset, 125_500, null, 0.42);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{trackId}";
|
||||
|
||||
// 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);
|
||||
|
||||
ResumePointResponse? resumePoint = JsonSerializer.Deserialize<ResumePointResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(resumePoint);
|
||||
Assert.Equal(resumePointId, resumePoint!.Id);
|
||||
Assert.Equal(libraryId, resumePoint.LibraryId);
|
||||
Assert.Equal(trackId, resumePoint.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, resumePoint.MediaKind);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, resumePoint.LastPosition.Kind);
|
||||
Assert.Equal(125.5, resumePoint.LastPosition.TimeOffsetSeconds);
|
||||
Assert.Null(resumePoint.LastPosition.Location);
|
||||
Assert.Equal(0.42, resumePoint.LastProgressFraction);
|
||||
Assert.Equal(s_lastConsumedOnUtc, resumePoint.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenResumePointDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"MediaResumePointNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WhenAnotherUsersResumePointExistsForTheSameItem_ShouldReturnNotFoundAndKeepOtherRow()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid otherResumePointId = await SeedResumePointAsync(otherUserId, Guid.NewGuid(), mediaItemId, MediaPositionKind.TimeOffset, 30_000, null, 0.3);
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{mediaItemId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
// The response must be indistinguishable from the one for a genuinely missing resume point.
|
||||
Dictionary<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(response);
|
||||
HttpResponseMessage missingResponse = await _client.GetAsync($"/api/v1/users/me/media-resume-points/MusicTrack/{Guid.NewGuid()}");
|
||||
Dictionary<string, JsonElement> missingProblem = await ReadProblemDetailsAsync(missingResponse);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode);
|
||||
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());
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaResumePointEntity? storedResumePoint = dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.Id == otherResumePointId);
|
||||
Assert.NotNull(storedResumePoint);
|
||||
Assert.Equal(otherUserId, storedResumePoint!.UserId);
|
||||
Assert.Equal(mediaItemId, storedResumePoint.MediaItemId);
|
||||
Assert.Equal(30_000, storedResumePoint.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal(0.3, storedResumePoint.LastProgressFraction);
|
||||
Assert.Equal(SEEDED_VERSION, storedResumePoint.Version);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetResumePoint_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnOwnResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid ownResumePointId = await SeedResumePointAsync(userId, libraryId, trackId, MediaPositionKind.TimeOffset, 125_500, null, 0.42);
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
Guid otherResumePointId = await SeedResumePointAsync(otherUserId, Guid.NewGuid(), Guid.NewGuid(), MediaPositionKind.TimeOffset, 60_000, null, 0.6);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{trackId}?userId={otherUserId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
ResumePointResponse? resumePoint = JsonSerializer.Deserialize<ResumePointResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(resumePoint);
|
||||
Assert.Equal(ownResumePointId, resumePoint!.Id);
|
||||
Assert.NotEqual(otherResumePointId, resumePoint.Id);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaResumePointEntity? storedResumePoint = dbContext.MediaResumePoints.FirstOrDefault(candidate => candidate.Id == otherResumePointId);
|
||||
Assert.NotNull(storedResumePoint);
|
||||
Assert.Equal(otherUserId, storedResumePoint!.UserId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")] // MediaKind.None, a defined enumeration member
|
||||
[InlineData("1")] // MediaKind.MusicTrack, a defined enumeration member
|
||||
public async Task GetResumePoint_WhenMediaKindIsNumeric_ShouldReturnUnsupportedMediaKindAndServeNoData(string numericMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
// A numeric route value that parses as a defined enumeration member must not be treated as a media kind, so the stored resume point is never served.
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, shouldTrackConsumptionProgress: true);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, trackId, MediaPositionKind.TimeOffset, 125_500, null, 0.42);
|
||||
string url = $"/api/v1/users/me/media-resume-points/{numericMediaKind}/{trackId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, url, "UnsupportedMediaKind");
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(resumePointId.ToString(), content, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.True(dbContext.MediaResumePoints.Any(candidate => candidate.Id == resumePointId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaResumePoints--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaResumePoints")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task GetResumePoint_WithSqlInjectionInMediaKind_ShouldRejectWithoutLeaking(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/media-resume-points/{Uri.EscapeDataString(maliciousMediaKind)}/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaResumePoints--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaResumePoints")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task GetResumePoint_WithSqlInjectionInMediaItemId_ShouldRejectWithoutLeaking(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/users/me/media-resume-points/MusicTrack/{Uri.EscapeDataString(maliciousMediaItemId)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="shouldTrackConsumptionProgress">Whether the library tracks the consumption progress of its items.</param>
|
||||
/// <returns>The Ids of the seeded library and track.</returns>
|
||||
private async Task<(Guid LibraryId, Guid TrackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, bool shouldTrackConsumptionProgress)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Music Library",
|
||||
libraryType: LibraryType.Music,
|
||||
contentLocations: [],
|
||||
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
|
||||
completionThresholdPercentage: shouldTrackConsumptionProgress ? 100 : null));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of a music track.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <param name="lastPositionKind">The kind of the position at which the item can be resumed.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The position, in milliseconds, when it is a time offset.</param>
|
||||
/// <param name="lastPositionLocation">The opaque locator, when it is a location.</param>
|
||||
/// <param name="lastProgressFraction">The progress fraction at which the item can be resumed.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
Guid mediaItemId,
|
||||
MediaPositionKind lastPositionKind,
|
||||
long? lastPositionTimeOffsetMilliseconds,
|
||||
string? lastPositionLocation,
|
||||
double lastProgressFraction)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
lastConsumedOnUtc: s_lastConsumedOnUtc,
|
||||
version: SEEDED_VERSION));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details document of <paramref name="response"/>.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The parsed problem details fields.</returns>
|
||||
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the standard validation problem of the get resume point route.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized resume point exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+514
@@ -0,0 +1,514 @@
|
||||
#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.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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.MediaConsumption.ReportConsumptionProgress;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.MediaConsumption.ReportConsumptionProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ReportConsumptionProgressEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReportConsumptionProgressEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const long SEEDED_VERSION = 7;
|
||||
|
||||
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 MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly ReportConsumptionProgressRequestFixture _reportConsumptionProgressRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportConsumptionProgressEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ReportConsumptionProgressEndpointTests(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 ReportConsumptionProgress_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/progress";
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.TimeOffset, 5_000, null);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 12.5, includeLocation: false),
|
||||
progressFraction: 0.35,
|
||||
consumedDurationInSeconds: 45);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
Assert.Equal(45.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.35, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(12.5, record.LastPosition.TimeOffsetSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenRecordDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReportConsumptionProgress_WhenAnotherUsersRecordIsTargeted_ShouldReturnNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherRecordId) = await SeedRecordAsync(otherUserId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 15_000, 0.2, MediaPositionKind.TimeOffset, 15_000, null);
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 90, includeLocation: false),
|
||||
progressFraction: 0.9,
|
||||
consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{otherRecordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(record => record.Id == otherRecordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedRecord.LastPositionKind);
|
||||
Assert.Equal(15_000, storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal(SEEDED_VERSION, storedRecord.Version);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ReportConsumptionProgress_WithSqlInjectionInRecordId_ShouldRejectWithoutLeaking(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Uri.EscapeDataString(maliciousRecordId)}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ReportConsumptionProgress_WithUnknownPositionKind_ShouldRejectWithoutLeaking(string maliciousPositionKind)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: maliciousPositionKind),
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, url, "InvalidMediaPosition");
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(maliciousPositionKind, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task ReportConsumptionProgress_WithOpaquePositionLocation_ShouldStoreItVerbatimWithoutLeaking(string location)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.Book, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.Location, null, "chapter-1");
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.Location), location: location, includeTimeOffsetSeconds: false),
|
||||
progressFraction: 0.4,
|
||||
consumedDurationInSeconds: 30);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/progress";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PutAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.NotNull(record!.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Equal(location, record.LastPosition.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(location, storedRecord!.LastPositionLocation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/> and a consumption record of a media item belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="mediaKind">The kind of media that the record consumes.</param>
|
||||
/// <param name="status">The state of the seeded session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionKind">The kind of the last known position.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The last known position, in milliseconds, when it is a time offset.</param>
|
||||
/// <param name="lastPositionLocation">The last known opaque locator, when it is a location.</param>
|
||||
/// <returns>The Ids of the seeded library and consumption record.</returns>
|
||||
private async Task<(Guid LibraryId, Guid RecordId)> SeedRecordAsync(
|
||||
Guid userId,
|
||||
MediaKind mediaKind,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
double lastProgressFraction,
|
||||
MediaPositionKind lastPositionKind,
|
||||
long? lastPositionTimeOffsetMilliseconds,
|
||||
string? lastPositionLocation)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Media Library",
|
||||
libraryType: mediaKind == MediaKind.Book ? LibraryType.EBook : LibraryType.Music,
|
||||
contentLocations: [],
|
||||
shouldTrackConsumptionProgress: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
version: SEEDED_VERSION));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the standard validation problem of the report consumption progress route.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized consumption record exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+467
@@ -0,0 +1,467 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.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.MediaConsumption.StartConsumption;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
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.MediaConsumption.StartConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="StartConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
|
||||
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 UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public StartConsumptionEndpointTests(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 StartConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/MusicTrack/{trackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.NotEqual(Guid.Empty, record!.Id);
|
||||
Assert.Equal(libraryId, record.LibraryId);
|
||||
Assert.Equal(trackId, record.MediaItemId);
|
||||
Assert.Equal(MediaKind.MusicTrack, record.MediaKind);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, record.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenMediaItemDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
Guid libraryId = await SeedLibraryAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"TrackNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartConsumption_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndCreateNoRecord()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(Guid otherLibraryId, Guid otherTrackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId);
|
||||
(Guid attackerId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/libraries/{otherLibraryId}/media-items/MusicTrack/{otherTrackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.Forbidden,
|
||||
"General.Unauthorized",
|
||||
"NotAuthorized",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.4");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(dbContext.MediaConsumptionRecords.Any(record => record.UserId == attackerId));
|
||||
Assert.Equal(otherUserId, dbContext.Libraries.First(library => library.Id == otherLibraryId).UserId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")] // MediaKind.None, a defined enumeration member
|
||||
[InlineData("1")] // MediaKind.MusicTrack, a defined enumeration member
|
||||
public async Task StartConsumption_WhenMediaKindIsNumeric_ShouldReturnUnsupportedMediaKindAndCreateNoRecord(string numericMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
// Only the member names are accepted as a media kind, so a numeric route value that parses as a defined enumeration member must be rejected before any record is created.
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(Guid libraryId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId);
|
||||
string url = $"/api/v1/libraries/{libraryId}/media-items/{numericMediaKind}/{trackId}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, url, "UnsupportedMediaKind");
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Assert.False(dbContext.MediaConsumptionRecords.Any(record => record.UserId == userId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StartConsumption_WithSqlInjectionInLibraryId_ShouldRejectWithoutLeaking(string maliciousLibraryId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/media-items/MusicTrack/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StartConsumption_WithSqlInjectionInMediaKind_ShouldRejectWithoutLeaking(string maliciousMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/{Uri.EscapeDataString(maliciousMediaKind)}/{Guid.NewGuid()}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StartConsumption_WithSqlInjectionInMediaItemId_ShouldRejectWithoutLeaking(string maliciousMediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
string url = $"/api/v1/libraries/{Guid.NewGuid()}/media-items/MusicTrack/{Uri.EscapeDataString(maliciousMediaItemId)}/consumption-records";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsync(url, null);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Ids of the seeded library and track.</returns>
|
||||
private async Task<(Guid LibraryId, Guid TrackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: []));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen"));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera"));
|
||||
dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/queen/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, trackId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the standard validation problem of the start consumption route.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized consumption record exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+516
@@ -0,0 +1,516 @@
|
||||
#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.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
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.MediaConsumption.StopConsumption;
|
||||
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.MediaConsumption.StopConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="StopConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const long SEEDED_VERSION = 7;
|
||||
|
||||
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 MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly StopConsumptionRequestFixture _stopConsumptionRequestFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
private readonly List<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public StopConsumptionEndpointTests(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 StopConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/stop";
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.TimeOffset, 5_000, null);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 30, includeLocation: false),
|
||||
progressFraction: 0.4,
|
||||
consumedDurationInSeconds: 60);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertNonCacheable(response);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
AssertNoDatabaseOnlyFields(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(recordId, record!.Id);
|
||||
Assert.Equal(ConsumptionStatus.Stopped, record.Status);
|
||||
Assert.NotNull(record.EndedOnUtc);
|
||||
Assert.Equal(60.0, record.ConsumedDurationInSeconds);
|
||||
Assert.Equal(0.4, record.LastProgressFraction);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, record.LastPosition!.Kind);
|
||||
Assert.Equal(30.0, record.LastPosition.TimeOffsetSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenRecordDoesNotExist_ShouldReturnNonCacheableNotFoundWithoutSensitiveData()
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNonCacheable(response);
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopConsumption_WhenAnotherUsersRecordIsTargeted_ShouldReturnNotFoundAndLeaveRecordUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
(Guid otherUserId, _) = await SeedOtherUserAsync();
|
||||
(_, Guid otherRecordId) = await SeedRecordAsync(otherUserId, MediaKind.MusicTrack, ConsumptionStatus.InProgress, 15_000, 0.2, MediaPositionKind.TimeOffset, 15_000, null);
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.TimeOffset), timeOffsetSeconds: 90, includeLocation: false),
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 90);
|
||||
string url = $"/api/v1/users/me/consumption-records/{otherRecordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertProblemDetailsAsync(
|
||||
response,
|
||||
HttpStatusCode.NotFound,
|
||||
"General.NotFound",
|
||||
"ConsumptionRecordNotFound",
|
||||
url,
|
||||
"https://tools.ietf.org/html/rfc9110#section-15.5.5");
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(record => record.Id == otherRecordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(ConsumptionStatus.InProgress, storedRecord!.Status);
|
||||
Assert.Null(storedRecord.EndedOnUtc);
|
||||
Assert.Equal(15_000, storedRecord.ConsumedDurationMilliseconds);
|
||||
Assert.Equal(0.2, storedRecord.LastProgressFraction);
|
||||
Assert.Equal(MediaPositionKind.TimeOffset, storedRecord.LastPositionKind);
|
||||
Assert.Equal(15_000, storedRecord.LastPositionTimeOffsetMilliseconds);
|
||||
Assert.Equal(SEEDED_VERSION, storedRecord.Version);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StopConsumption_WithSqlInjectionInRecordId_ShouldRejectWithoutLeaking(string maliciousRecordId)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(includePosition: false, progressFraction: 0.5, consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Uri.EscapeDataString(maliciousRecordId)}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
await AssertRejectedInjectionAsync(response, maliciousRecordId, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StopConsumption_WithUnknownPositionKind_ShouldRejectWithoutLeaking(string maliciousPositionKind)
|
||||
{
|
||||
// Arrange
|
||||
await CreateAuthenticatedUserAsync(_client);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: maliciousPositionKind),
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 10);
|
||||
string url = $"/api/v1/users/me/consumption-records/{Guid.NewGuid()}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
string content = await AssertValidationProblemAsync(response, url, "InvalidMediaPosition");
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(maliciousPositionKind, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("' OR '1'='1")] // boolean-based injection
|
||||
[InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
|
||||
[InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
|
||||
[InlineData("../../../etc/passwd")] // path traversal
|
||||
[InlineData("<script>alert(1)</script>")] // markup injection
|
||||
public async Task StopConsumption_WithOpaquePositionLocation_ShouldStoreItVerbatimWithoutLeaking(string location)
|
||||
{
|
||||
// Arrange
|
||||
(Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
|
||||
(_, Guid recordId) = await SeedRecordAsync(userId, MediaKind.Book, ConsumptionStatus.InProgress, 0, 0.1, MediaPositionKind.Location, null, "chapter-1");
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: _mediaPositionRequestFixture.Create(kind: nameof(MediaPositionKind.Location), location: location, includeTimeOffsetSeconds: false),
|
||||
progressFraction: 0.4,
|
||||
consumedDurationInSeconds: 30);
|
||||
string url = $"/api/v1/users/me/consumption-records/{recordId}/stop";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.PostAsJsonAsync(url, request);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
AssertNoSensitiveData(content);
|
||||
|
||||
ConsumptionRecordResponse? record = JsonSerializer.Deserialize<ConsumptionRecordResponse>(content, _jsonOptions);
|
||||
Assert.NotNull(record);
|
||||
Assert.Equal(ConsumptionStatus.Stopped, record!.Status);
|
||||
Assert.NotNull(record.LastPosition);
|
||||
Assert.Equal(MediaPositionKind.Location, record.LastPosition!.Kind);
|
||||
Assert.Equal(location, record.LastPosition.Location);
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
MediaConsumptionRecordEntity? storedRecord = dbContext.MediaConsumptionRecords.FirstOrDefault(candidate => candidate.Id == recordId);
|
||||
Assert.NotNull(storedRecord);
|
||||
Assert.Equal(location, storedRecord!.LastPositionLocation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/> and a consumption record of a media item belonging to it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="mediaKind">The kind of media that the record consumes.</param>
|
||||
/// <param name="status">The state of the seeded session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The consumed duration of the record, in milliseconds.</param>
|
||||
/// <param name="lastProgressFraction">The last reported progress fraction of the record.</param>
|
||||
/// <param name="lastPositionKind">The kind of the last known position.</param>
|
||||
/// <param name="lastPositionTimeOffsetMilliseconds">The last known position, in milliseconds, when it is a time offset.</param>
|
||||
/// <param name="lastPositionLocation">The last known opaque locator, when it is a location.</param>
|
||||
/// <returns>The Ids of the seeded library and consumption record.</returns>
|
||||
private async Task<(Guid LibraryId, Guid RecordId)> SeedRecordAsync(
|
||||
Guid userId,
|
||||
MediaKind mediaKind,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
double lastProgressFraction,
|
||||
MediaPositionKind lastPositionKind,
|
||||
long? lastPositionTimeOffsetMilliseconds,
|
||||
string? lastPositionLocation)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(
|
||||
id: libraryId,
|
||||
userId: userId,
|
||||
title: "Media Library",
|
||||
libraryType: mediaKind == MediaKind.Book ? LibraryType.EBook : LibraryType.Music,
|
||||
contentLocations: [],
|
||||
shouldTrackConsumptionProgress: false));
|
||||
dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: lastPositionKind,
|
||||
lastPositionTimeOffsetMilliseconds: lastPositionTimeOffsetMilliseconds,
|
||||
lastPositionLocation: lastPositionLocation,
|
||||
lastProgressFraction: lastProgressFraction,
|
||||
consecutivePagesRead: 0,
|
||||
version: SEEDED_VERSION));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return (libraryId, recordId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
AssertNoSensitiveData(content);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="statusCode">The expected HTTP status code.</param>
|
||||
/// <param name="expectedTitle">The expected problem title.</param>
|
||||
/// <param name="expectedDetail">The expected problem detail.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedType">The expected problem type URI.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertProblemDetailsAsync(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
|
||||
{
|
||||
Assert.Equal(statusCode, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal(expectedType, problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedTitle, problemDetails["title"].GetString());
|
||||
Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the standard validation problem of the stop consumption route.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals or reaching the data access layer.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
|
||||
{
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
// The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
|
||||
string escapedPayload = Uri.EscapeDataString(payload);
|
||||
int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
|
||||
Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// A payload that carries encoded path separators is rejected by routing before it reaches the validator. That is still a safe rejection, so only it may take this branch.
|
||||
Assert.Contains("/", payload, StringComparison.Ordinal);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
AssertNoSensitiveData(content);
|
||||
Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the per-user responses are not storable by any intermediary and vary by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized consumption record exposes only the fields of its documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+1
@@ -80,6 +80,7 @@ public class StartConsumptionCommandValidatorTests
|
||||
[InlineData(" ")] // the media kind is whitespace only
|
||||
[InlineData("Hologram")] // the media kind is not a member of the enumeration
|
||||
[InlineData("0")] // the media kind is a numeric route value, which the validator rejects by name
|
||||
[InlineData("1")] // a numeric route value that parses to the defined MusicTrack member, which the old Enum.TryParse and Enum.IsDefined logic accepted
|
||||
public void Validate_WhenMediaKindIsEmptyOrUnsupported_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
+18
@@ -266,6 +266,8 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(DomainErrors.MediaConsumption.MediaResumePointNotFound, result.FirstError);
|
||||
await _mockMediaResumePointRepository.Received(1).DeleteForUserAndMediaItemAsync(_userId, MediaKind.MusicTrack, mediaItemId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
// The query answers with a not-found result, which the request pipeline does not commit, so the cleanup is committed explicitly.
|
||||
await _mockUnitOfWork.Received(1).CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -289,6 +291,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -309,6 +312,8 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.MediaConsumption.MediaResumePointNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
// A concurrency conflict means the row is already gone, which is the desired outcome, so there is nothing to commit.
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -329,6 +334,7 @@ public class GetResumePointQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -352,6 +358,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteForUserAndMediaItemAsync(Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -374,6 +381,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockMediaResumePointRepository.Received(1).DeleteForUserAndMediaItemAsync(_userId, MediaKind.MusicTrack, mediaItemId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -395,6 +403,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockMediaResumePointRepository.Received(1).DeleteForUserAndMediaItemAsync(_userId, MediaKind.MusicTrack, mediaItemId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -419,6 +428,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -441,6 +451,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -463,6 +474,7 @@ public class GetResumePointQueryHandlerTests
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -511,6 +523,7 @@ public class GetResumePointQueryHandlerTests
|
||||
cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteForUserAndMediaItemAsync(Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -529,6 +542,7 @@ public class GetResumePointQueryHandlerTests
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -554,6 +568,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteForUserAndMediaItemAsync(Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -578,6 +593,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockMediaResumePointRepository.Received(1).DeleteForUserAndMediaItemAsync(_userId, MediaKind.Book, mediaItemId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
@@ -603,6 +619,7 @@ public class GetResumePointQueryHandlerTests
|
||||
Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
|
||||
await _mockMediaResumePointRepository.Received(1).DeleteForUserAndMediaItemAsync(_userId, MediaKind.Book, mediaItemId, Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -654,6 +671,7 @@ public class GetResumePointQueryHandlerTests
|
||||
cancellationToken: Arg.Any<CancellationToken>());
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteForUserAndMediaItemAsync(Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().CommitTransactionAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+1
@@ -38,6 +38,7 @@ public class GetResumePointQueryValidatorTests
|
||||
[InlineData(" ")] // the media kind is whitespace only
|
||||
[InlineData("not-a-media-kind")] // the media kind is not the name of a defined kind
|
||||
[InlineData("99999")] // a numeric value that is not the name of a defined kind
|
||||
[InlineData("1")] // a numeric value that parses to the defined MusicTrack member, which the old Enum.TryParse and Enum.IsDefined logic accepted
|
||||
public void Validate_WhenMediaKindIsNotTheNameOfADefinedKind_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.CompleteConsumption;
|
||||
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.MediaConsumption.CompleteConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CompleteConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CompleteConsumptionEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<CompleteConsumptionCommand, Result<ConsumptionRecordResponse>> _mockHandler;
|
||||
private readonly CompleteConsumptionEndpoint _sut;
|
||||
private readonly CompleteConsumptionRequestFixture _completeConsumptionRequestFixture = new();
|
||||
private readonly MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly ConsumptionRecordResponseFixture _consumptionRecordResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompleteConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public CompleteConsumptionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<CompleteConsumptionCommand, Result<ConsumptionRecordResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<CompleteConsumptionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionRecordResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
ConsumptionRecordResponse expectedResponse = _consumptionRecordResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ConsumptionRecordResponse> okResult = Assert.IsType<Ok<ConsumptionRecordResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.InvalidProgressFraction, DomainErrors.MediaConsumption.ConsumedDurationMustBeNonNegative];
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "InvalidProgressFraction", "ConsumedDurationMustBeNonNegative" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConsecutivePagesForNonPageBasedMediaError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia;
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Forbidden", problemDetails.Title);
|
||||
Assert.Equal("ConsecutivePagesReadIsOnlySupportedForPageBasedMedia", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnConflictProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionIsAlreadyTerminal;
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails.Status);
|
||||
Assert.Equal("General.Conflict", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionIsAlreadyTerminal", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsATimeOffset_ShouldSendCommandWithTimeOffsetPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.TimeOffset),
|
||||
timeOffsetSeconds: 987.25);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 3600,
|
||||
consecutivePagesRead: 0);
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
// The request carries no record Id, so the command takes the identifier from the route only.
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<CompleteConsumptionCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.TimeOffset) &&
|
||||
command.PositionTimeOffsetInSeconds == 987.25 &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 1 &&
|
||||
command.ConsumedDurationInSeconds == 3600 &&
|
||||
command.ConsecutivePagesRead == 0),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsALocation_ShouldSendCommandWithLocationPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.Location),
|
||||
location: "page-42",
|
||||
includeTimeOffsetSeconds: false);
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 0.95,
|
||||
consumedDurationInSeconds: 1800,
|
||||
consecutivePagesRead: 42);
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<CompleteConsumptionCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.Location) &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == "page-42" &&
|
||||
command.ProgressFraction == 0.95 &&
|
||||
command.ConsumedDurationInSeconds == 1800 &&
|
||||
command.ConsecutivePagesRead == 42),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOptionalValuesAreNotSupplied_ShouldSendCommandWithNullPositionAndNullConsecutivePages()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
includePosition: false,
|
||||
includeConsecutivePagesRead: false,
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 3600);
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<CompleteConsumptionCommand>(command =>
|
||||
command.PositionKind == null &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 1 &&
|
||||
command.ConsumedDurationInSeconds == 3600 &&
|
||||
command.ConsecutivePagesRead == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullRecordId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
CompleteConsumptionRequest request = _completeConsumptionRequestFixture.Create(
|
||||
progressFraction: 1,
|
||||
consumedDurationInSeconds: 3600);
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("recordId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<CompleteConsumptionCommand>(command => command.ConsumptionRecordId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<CompleteConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_consumptionRecordResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_completeConsumptionRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.GetConsumptionRecord;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.MediaConsumption.GetConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionRecordEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetConsumptionRecordQuery, Result<ConsumptionRecordResponse>> _mockHandler;
|
||||
private readonly GetConsumptionRecordEndpoint _sut;
|
||||
private readonly ConsumptionRecordResponseFixture _consumptionRecordResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetConsumptionRecordEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetConsumptionRecordQuery, Result<ConsumptionRecordResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetConsumptionRecordEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionRecordResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ConsumptionRecordResponse expectedResponse = _consumptionRecordResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ConsumptionRecordResponse> okResult = Assert.IsType<Ok<ConsumptionRecordResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "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<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetConsumptionRecordQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetConsumptionRecordQuery>(query => query.ConsumptionRecordId == recordId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("recordId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetConsumptionRecordQuery>(query => query.ConsumptionRecordId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetConsumptionRecordQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_consumptionRecordResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.GetResumePoint;
|
||||
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.MediaConsumption.GetResumePoint;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetResumePointEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetResumePointEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetResumePointQuery, Result<ResumePointResponse>> _mockHandler;
|
||||
private readonly GetResumePointEndpoint _sut;
|
||||
private readonly ResumePointResponseFixture _resumePointResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetResumePointEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetResumePointEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetResumePointQuery, Result<ResumePointResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetResumePointEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithResumePointResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ResumePointResponse expectedResponse = _resumePointResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "Book";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = mediaItemId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ResumePointResponse> okResult = Assert.IsType<Ok<ResumePointResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_resumePointResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = DomainErrors.MediaConsumption.MediaResumePointNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.UnsupportedMediaKind, DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "UnsupportedMediaKind", "MediaItemIdCannotBeEmpty" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsMediaKindCannotResumeError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.MediaKindCannotResume;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Forbidden", problemDetails.Title);
|
||||
Assert.Equal("MediaKindCannotResume", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.MediaResumePointNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("MediaResumePointNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetResumePointQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_resumePointResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "MusicTrack";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = mediaItemId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetResumePointQuery>(query =>
|
||||
query.MediaKind == "MusicTrack" &&
|
||||
query.MediaItemId == mediaItemId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendQueryWithNullRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_resumePointResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("mediaKind");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("mediaItemId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetResumePointQuery>(query =>
|
||||
query.MediaKind == null &&
|
||||
query.MediaItemId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetResumePointQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_resumePointResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "MusicTrack";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+345
@@ -0,0 +1,345 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.ReportConsumptionProgress;
|
||||
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.MediaConsumption.ReportConsumptionProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ReportConsumptionProgressEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReportConsumptionProgressEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<ReportConsumptionProgressCommand, Result<ConsumptionRecordResponse>> _mockHandler;
|
||||
private readonly ReportConsumptionProgressEndpoint _sut;
|
||||
private readonly ReportConsumptionProgressRequestFixture _reportConsumptionProgressRequestFixture = new();
|
||||
private readonly MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly ConsumptionRecordResponseFixture _consumptionRecordResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportConsumptionProgressEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ReportConsumptionProgressEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<ReportConsumptionProgressCommand, Result<ConsumptionRecordResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<ReportConsumptionProgressEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionRecordResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
ConsumptionRecordResponse expectedResponse = _consumptionRecordResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ConsumptionRecordResponse> okResult = Assert.IsType<Ok<ConsumptionRecordResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.InvalidMediaPosition, DomainErrors.MediaConsumption.InvalidProgressFraction];
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "InvalidMediaPosition", "InvalidProgressFraction" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnConflictProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionIsNotInProgress;
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails.Status);
|
||||
Assert.Equal("General.Conflict", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionIsNotInProgress", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsATimeOffset_ShouldSendCommandWithTimeOffsetPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.TimeOffset),
|
||||
timeOffsetSeconds: 1234.5);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 0.25,
|
||||
consumedDurationInSeconds: 300,
|
||||
consecutivePagesRead: 4);
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
// The request carries no record Id, so the command takes the identifier from the route only.
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ReportConsumptionProgressCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.TimeOffset) &&
|
||||
command.PositionTimeOffsetInSeconds == 1234.5 &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 0.25 &&
|
||||
command.ConsumedDurationInSeconds == 300 &&
|
||||
command.ConsecutivePagesRead == 4),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsALocation_ShouldSendCommandWithLocationPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.Location),
|
||||
location: "chapter-3",
|
||||
includeTimeOffsetSeconds: false);
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 0.75,
|
||||
consumedDurationInSeconds: 600,
|
||||
consecutivePagesRead: 12);
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ReportConsumptionProgressCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.Location) &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == "chapter-3" &&
|
||||
command.ProgressFraction == 0.75 &&
|
||||
command.ConsumedDurationInSeconds == 600 &&
|
||||
command.ConsecutivePagesRead == 12),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsNotSupplied_ShouldSendCommandWithNullPositionAndDefaultConsecutivePagesRead()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
includePosition: false,
|
||||
includeConsecutivePagesRead: false,
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 120);
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ReportConsumptionProgressCommand>(command =>
|
||||
command.PositionKind == null &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 0.5 &&
|
||||
command.ConsumedDurationInSeconds == 120 &&
|
||||
command.ConsecutivePagesRead == 0),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullRecordId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ReportConsumptionProgressRequest request = _reportConsumptionProgressRequestFixture.Create(
|
||||
progressFraction: 0.5,
|
||||
consumedDurationInSeconds: 120);
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("recordId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<ReportConsumptionProgressCommand>(command => command.ConsumptionRecordId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<ReportConsumptionProgressCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_consumptionRecordResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_reportConsumptionProgressRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.StartConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.StartConsumption;
|
||||
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.MediaConsumption.StartConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StartConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartConsumptionEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<StartConsumptionCommand, Result<ConsumptionRecordResponse>> _mockHandler;
|
||||
private readonly StartConsumptionEndpoint _sut;
|
||||
private readonly ConsumptionRecordResponseFixture _consumptionRecordResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StartConsumptionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<StartConsumptionCommand, Result<ConsumptionRecordResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<StartConsumptionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionRecordResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ConsumptionRecordResponse expectedResponse = _consumptionRecordResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "MusicTrack";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = mediaItemId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ConsumptionRecordResponse> okResult = Assert.IsType<Ok<ConsumptionRecordResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.Library.LibraryIdCannotBeEmpty, DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty];
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "LibraryIdCannotBeEmpty", "MediaItemIdCannotBeEmpty" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsUnsupportedMediaKindError_ShouldReturnValidationProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.UnsupportedMediaKind;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal(new[] { "UnsupportedMediaKind" }, validationProblemDetails.Errors["General.Validation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsLibraryNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.Library.LibraryNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("LibraryNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsTrackNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.Music.TrackNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("TrackNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsBookNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.WrittenContent.BookNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("BookNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConcurrencyConflictError_ShouldReturnConflictProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Persistence.ConcurrencyConflict;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails.Status);
|
||||
Assert.Equal("General.Conflict", problemDetails.Title);
|
||||
Assert.Equal("ConcurrencyConflict", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendStartConsumptionCommandToSender()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "Book";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = mediaItemId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StartConsumptionCommand>(command =>
|
||||
command.LibraryId == libraryId.ToString() &&
|
||||
command.MediaKind == "Book" &&
|
||||
command.MediaItemId == mediaItemId.ToString()),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithRawRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = "not-a-library-guid";
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "not-a-media-kind";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = "not-a-guid";
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StartConsumptionCommand>(command =>
|
||||
command.LibraryId == "not-a-library-guid" &&
|
||||
command.MediaKind == "not-a-media-kind" &&
|
||||
command.MediaItemId == "not-a-guid"),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullRouteValues()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("libraryId");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("mediaKind");
|
||||
_sut.HttpContext.Request.RouteValues.Remove("mediaItemId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StartConsumptionCommand>(command =>
|
||||
command.LibraryId == null &&
|
||||
command.MediaKind == null &&
|
||||
command.MediaItemId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<StartConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_consumptionRecordResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString();
|
||||
_sut.HttpContext.Request.RouteValues["mediaKind"] = "MusicTrack";
|
||||
_sut.HttpContext.Request.RouteValues["mediaItemId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
|
||||
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.MediaConsumption;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.MediaConsumption.StopConsumption;
|
||||
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.MediaConsumption.StopConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StopConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopConsumptionEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<StopConsumptionCommand, Result<ConsumptionRecordResponse>> _mockHandler;
|
||||
private readonly StopConsumptionEndpoint _sut;
|
||||
private readonly StopConsumptionRequestFixture _stopConsumptionRequestFixture = new();
|
||||
private readonly MediaPositionRequestFixture _mediaPositionRequestFixture = new();
|
||||
private readonly ConsumptionRecordResponseFixture _consumptionRecordResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StopConsumptionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<StopConsumptionCommand, Result<ConsumptionRecordResponse>>>();
|
||||
_sut = FastEndpoints.Factory.Create<StopConsumptionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithConsumptionRecordResponse()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
ConsumptionRecordResponse expectedResponse = _consumptionRecordResponseFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<ConsumptionRecordResponse> okResult = Assert.IsType<Ok<ConsumptionRecordResponse>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// 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_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.InvalidProgressFraction, DomainErrors.MediaConsumption.ConsumedDurationMustBeNonNegative];
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "InvalidProgressFraction", "ConsumedDurationMustBeNonNegative" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConsumedDurationCannotDecreaseError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumedDurationCannotDecrease;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Forbidden", problemDetails.Title);
|
||||
Assert.Equal("ConsumedDurationCannotDecrease", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsConflictError_ShouldReturnConflictProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create();
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionIsAlreadyTerminal;
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status409Conflict, problemDetails.Status);
|
||||
Assert.Equal("General.Conflict", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionIsAlreadyTerminal", problemDetails.Detail);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsATimeOffset_ShouldSendCommandWithTimeOffsetPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.TimeOffset),
|
||||
timeOffsetSeconds: 431.5);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 0.4,
|
||||
consumedDurationInSeconds: 400,
|
||||
consecutivePagesRead: 0);
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
// The request carries no record Id, so the command takes the identifier from the route only.
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StopConsumptionCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.TimeOffset) &&
|
||||
command.PositionTimeOffsetInSeconds == 431.5 &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 0.4 &&
|
||||
command.ConsumedDurationInSeconds == 400 &&
|
||||
command.ConsecutivePagesRead == 0),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenPositionIsALocation_ShouldSendCommandWithLocationPosition()
|
||||
{
|
||||
// Arrange
|
||||
Guid recordId = Guid.NewGuid();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
MediaPositionRequest position = _mediaPositionRequestFixture.Create(
|
||||
kind: nameof(MediaPositionKind.Location),
|
||||
location: "page-17",
|
||||
includeTimeOffsetSeconds: false);
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
position: position,
|
||||
progressFraction: 0.3,
|
||||
consumedDurationInSeconds: 900,
|
||||
consecutivePagesRead: 17);
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = recordId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StopConsumptionCommand>(command =>
|
||||
command.ConsumptionRecordId == recordId.ToString() &&
|
||||
command.PositionKind == nameof(MediaPositionKind.Location) &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == "page-17" &&
|
||||
command.ProgressFraction == 0.3 &&
|
||||
command.ConsumedDurationInSeconds == 900 &&
|
||||
command.ConsecutivePagesRead == 17),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOptionalValuesAreNotSupplied_ShouldSendCommandWithNullPositionAndNullConsecutivePages()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
includePosition: false,
|
||||
includeConsecutivePagesRead: false,
|
||||
progressFraction: 0.2,
|
||||
consumedDurationInSeconds: 200);
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StopConsumptionCommand>(command =>
|
||||
command.PositionKind == null &&
|
||||
command.PositionTimeOffsetInSeconds == null &&
|
||||
command.PositionLocation == null &&
|
||||
command.ProgressFraction == 0.2 &&
|
||||
command.ConsumedDurationInSeconds == 200 &&
|
||||
command.ConsecutivePagesRead == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullRecordId()
|
||||
{
|
||||
// Arrange
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
StopConsumptionRequest request = _stopConsumptionRequestFixture.Create(
|
||||
progressFraction: 0.2,
|
||||
consumedDurationInSeconds: 200);
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_consumptionRecordResponseFixture.Create()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("recordId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<StopConsumptionCommand>(command => command.ConsumptionRecordId == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<StopConsumptionCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(_consumptionRecordResponseFixture.Create());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["recordId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(_stopConsumptionRequestFixture.Create(), cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user