mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 15:11:10 +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
+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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user