mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 16:11:10 +00:00
Implements tests for commit dfd979ec1e
This commit is contained in:
1 parent
d8adf3c1b6
commit
968061e89a
111 files changed
+19955
-292
No files matched your search
+357
@@ -0,0 +1,357 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 5, 8, 20, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 5, 9, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserHasHistory_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(15));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalled_ShouldPreserveTheCurrentUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(firstResumePointId, secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUserHasNoHistory_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/consumption-history");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+367
@@ -0,0 +1,367 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserConsumptionHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 6, 12, 10, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 6, 12, 55, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserConsumptionHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenCurrentUserNamesThemselves_ShouldDeleteEveryRecordOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{userId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenAdminNamesAnotherUser_ShouldDeleteEveryRecordOfThatUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid firstRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid secondRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(20));
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(firstRecordId, secondRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserConsumptionHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 7, 21, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 7, 21, 35, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyTheCurrentUsersResumePointsInThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsOmitted_ShouldDeleteEveryResumePointOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync("/api/v1/users/me/media-resume-points");
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+458
@@ -0,0 +1,458 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearUserResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearUserResumePointsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 8, 10, 30, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 8, 11, 10, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearUserResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public ClearUserResumePointsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenCurrentUserNamesThemselves_ShouldDeleteEveryResumePoint()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, firstLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId, secondResumePointId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsSupplied_ShouldDeleteOnlyThatLibrarysResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid firstLibraryId = await SeedLibraryAsync(userId, "First User Library");
|
||||
Guid secondLibraryId = await SeedLibraryAsync(userId, "Second User Library");
|
||||
Guid firstResumePointId = await SeedResumePointAsync(userId, firstLibraryId, Guid.NewGuid());
|
||||
Guid secondResumePointId = await SeedResumePointAsync(userId, secondLibraryId, Guid.NewGuid());
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, firstLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{userId}/media-resume-points?libraryId={firstLibraryId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(firstResumePointId);
|
||||
await AssertResumePointsArePreservedAsync(secondResumePointId, otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserResumePointId = await SeedResumePointAsync(otherUserId, otherUserLibraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/{otherUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsArePreservedAsync(otherUserResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetResumePointId = await SeedResumePointAsync(targetUserId, targetLibraryId, Guid.NewGuid());
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertResumePointsAreDeletedAsync(targetResumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenLibraryIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/media-resume-points";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearUserResumePoints_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/media-resume-points";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be deleted.</param>
|
||||
private async Task AssertResumePointsAreDeletedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
if (storedResumePoints.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedResumePoints);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionRecordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 2, 20, 15, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 2, 20, 45, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly MediaResumePointEntityFixture _mediaResumePointEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordBelongsToCurrentUser_ShouldDeleteOnlyThatRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc.AddMinutes(10));
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordDoesNotExist_ShouldSucceedWithoutSideEffects()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(existingRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/me/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenCalled_ShouldPreserveTheUsersResumePoints()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid resumePointId = await SeedResumePointAsync(userId, libraryId, Guid.NewGuid());
|
||||
string url = $"/api/v1/users/me/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
await AssertResumePointsArePreservedAsync(resumePointId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/me/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a resume point of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the resume point.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <returns>The Id of the seeded resume point.</returns>
|
||||
private async Task<Guid> SeedResumePointAsync(Guid userId, Guid libraryId, Guid mediaItemId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid resumePointId = Guid.NewGuid();
|
||||
dbContext.MediaResumePoints.Add(_mediaResumePointEntityFixture.Create(
|
||||
id: resumePointId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: mediaItemId,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
lastConsumedOnUtc: s_lastActivityOnUtc));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return resumePointId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the resume points identified by <paramref name="resumePointIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="resumePointIds">The Ids of the resume points that must be preserved.</param>
|
||||
private async Task AssertResumePointsArePreservedAsync(params Guid[] resumePointIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaResumePointEntity> storedResumePoints = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a resume point that must survive is read until
|
||||
// that completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedResumePoints = await dbContext.MediaResumePoints.AsNoTracking()
|
||||
.Where(resumePoint => resumePointIds.Contains(resumePoint.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(resumePointIds.Length, storedResumePoints.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+401
@@ -0,0 +1,401 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteUserConsumptionRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionRecordEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 4, 3, 18, 5, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 3, 18, 40, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionRecordEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionRecordEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenCurrentUserNamesThemselves_ShouldDeleteTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{recordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(recordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedOtherUserAsync();
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, "Target User Library");
|
||||
Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
string url = $"/api/v1/users/{targetUserId}/consumption-history/{targetRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsAreDeletedAsync(targetRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordBelongsToAnotherUser_ShouldSucceedAndPreserveThatUsersRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, "Current User Library");
|
||||
Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
Guid otherUserId = await SeedOtherUserAsync();
|
||||
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
|
||||
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, s_startedOnUtc, s_lastActivityOnUtc);
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/{otherUserRecordId}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
await AssertConsumptionRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUserIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = $"/api/v1/users/not-a-guid/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenRecordIdIsNotAGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string url = $"/api/v1/users/{userId}/consumption-history/not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "ConsumptionRecordIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteUserConsumptionRecord_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/{Guid.NewGuid()}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(Guid userId, Guid libraryId, DateTime startedOnUtc, DateTime lastActivityOnUtc)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
status: ConsumptionStatus.Stopped,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: 90_000,
|
||||
lastPositionKind: MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: 45_000,
|
||||
lastPositionLocation: null,
|
||||
lastProgressFraction: 0.5,
|
||||
consecutivePagesRead: 0);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertConsumptionRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
|
||||
// has run, instead of assuming that it already has.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
if (storedRecords.Count == 0)
|
||||
return;
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Empty(storedRecords);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertConsumptionRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> storedRecords = [];
|
||||
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
|
||||
// completion has run, instead of trusting the state observed right after the response.
|
||||
for (int attempt = 0; attempt < 20; attempt++)
|
||||
{
|
||||
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
|
||||
.Where(record => recordIds.Contains(record.Id))
|
||||
.ToListAsync();
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
await Task.Delay(100);
|
||||
}
|
||||
Assert.Equal(recordIds.Length, storedRecords.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_musicStartedOnUtc = new(2026, 3, 10, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 10, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated admin API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdmin_ShouldReturnPerUserSummariesAndCombinedTotals()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, Guid secondUserLibraryId) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
|
||||
ConsumptionSummaryResponse firstUser = Assert.Single(statistics!.Users, summary => summary.UserId == firstUserId);
|
||||
Assert.Equal(100d, firstUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, firstUser.CountedSessionCount);
|
||||
Assert.Equal(1, firstUser.CompletedSessionCount);
|
||||
Assert.Equal(1, firstUser.StoppedSessionCount);
|
||||
Assert.Equal(0.5, firstUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse firstUserMusic = Assert.Single(firstUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, firstUserMusic.MediaKind);
|
||||
Assert.Equal(100d, firstUserMusic.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
ConsumptionSummaryResponse secondUser = Assert.Single(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
Assert.Equal(400d, secondUser.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, secondUser.CountedSessionCount);
|
||||
Assert.Equal(1, secondUser.CompletedSessionCount);
|
||||
Assert.Equal(0, secondUser.StoppedSessionCount);
|
||||
Assert.Equal(1d, secondUser.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse secondUserBook = Assert.Single(secondUser.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, secondUserBook.MediaKind);
|
||||
Assert.Equal(400d, secondUserBook.TotalConsumedDurationInSeconds, 3);
|
||||
|
||||
Assert.Equal(statistics.Users.Select(summary => summary.UserId).Order().ToArray(), statistics.Users.Select(summary => summary.UserId).ToArray());
|
||||
Assert.NotEqual(firstUserLibraryId, secondUserLibraryId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByRegularUser_ShouldReturnForbiddenWithExactShape()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient regularClient = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await regularClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("users"));
|
||||
Assert.False(problemDetails.ContainsKey("total"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyTheUsersOfThatLibrary()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, Guid firstUserLibraryId) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?libraryId={firstUserLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
ConsumptionSummaryResponse user = Assert.Single(statistics!.Users);
|
||||
Assert.Equal(firstUserId, user.UserId);
|
||||
Assert.Equal(100d, user.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(100d, statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(1, statistics.Total.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse totalMusic = Assert.Single(statistics.Total.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, totalMusic.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
Assert.NotEmpty(statistics!.Users);
|
||||
Assert.All(statistics.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToStartDate_ShouldExcludeEarlierSessions()
|
||||
{
|
||||
// Arrange
|
||||
await SeedMusicOnlyUserAsync();
|
||||
(Guid secondUserId, _) = await SeedBookOnlyUserAsync();
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every book record of this class starts in February, so a March start date can only leave music sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.MusicTrack, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == secondUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenRestrictedToEndDate_ShouldExcludeLaterSessions()
|
||||
{
|
||||
// Arrange
|
||||
(Guid firstUserId, _) = await SeedMusicOnlyUserAsync();
|
||||
await SeedBookOnlyUserAsync();
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AllUsersConsumptionStatisticsResponse? statistics = await DeserializeAsync<AllUsersConsumptionStatisticsResponse>(response);
|
||||
Assert.NotNull(statistics);
|
||||
// Every music record of this class starts in March, so a February end date can only leave book sessions in the summary.
|
||||
Assert.All(statistics!.Users, summary => Assert.All(summary.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind)));
|
||||
Assert.All(statistics.Total.MediaKindSummaries, kind => Assert.Equal(MediaKind.Book, kind.MediaKind));
|
||||
Assert.DoesNotContain(statistics.Users, summary => summary.UserId == firstUserId);
|
||||
AssertTotalsMatchUsers(statistics);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenTargetUserIdQueryParameterIsNotAValidGuid_ShouldIgnoreIt()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/consumption-statistics?userId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the combined totals are exactly the sum of the returned user summaries.
|
||||
/// </summary>
|
||||
/// <param name="statistics">The all users statistics response to assert on.</param>
|
||||
private static void AssertTotalsMatchUsers(AllUsersConsumptionStatisticsResponse statistics)
|
||||
{
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.TotalConsumedDurationInSeconds), statistics.Total.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CountedSessionCount), statistics.Total.CountedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.CompletedSessionCount), statistics.Total.CompletedSessionCount);
|
||||
Assert.Equal(statistics.Users.Sum(summary => summary.StoppedSessionCount), statistics.Total.StoppedSessionCount);
|
||||
double expectedCompletionRate = statistics.Total.CountedSessionCount == 0
|
||||
? 0
|
||||
: (double)statistics.Total.CompletedSessionCount / statistics.Total.CountedSessionCount;
|
||||
Assert.Equal(expectedCompletionRate, statistics.Total.CompletionRate, 6);
|
||||
|
||||
MediaKind[] expectedMediaKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Select(summary => summary.MediaKind)
|
||||
.Distinct()
|
||||
.Order()];
|
||||
Assert.Equal(expectedMediaKinds, statistics.Total.MediaKindSummaries.Select(summary => summary.MediaKind).ToArray());
|
||||
foreach (MediaKindConsumptionSummaryResponse totalKind in statistics.Total.MediaKindSummaries)
|
||||
{
|
||||
List<MediaKindConsumptionSummaryResponse> userKinds = [.. statistics.Users
|
||||
.SelectMany(summary => summary.MediaKindSummaries)
|
||||
.Where(summary => summary.MediaKind == totalKind.MediaKind)];
|
||||
Assert.Equal(userKinds.Sum(summary => summary.TotalConsumedDurationInSeconds), totalKind.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CountedSessionCount), totalKind.CountedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.CompletedSessionCount), totalKind.CompletedSessionCount);
|
||||
Assert.Equal(userKinds.Sum(summary => summary.StoppedSessionCount), totalKind.StoppedSessionCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with a music library and two counted music sessions.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its music library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedMusicOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"musicuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_musicStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_musicStartedOnUtc.AddMinutes(5), 40_000, 0);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user with an ebook library and one counted book session and one uncounted one.
|
||||
/// </summary>
|
||||
/// <returns>The Ids of the seeded user and of its ebook library.</returns>
|
||||
private async Task<(Guid userId, Guid libraryId)> SeedBookOnlyUserAsync()
|
||||
{
|
||||
Guid userId = await SeedUserAsync($"bookuser_{Guid.NewGuid()}");
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStartedOnUtc.AddMinutes(5), 100_000, 1);
|
||||
return (userId, libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The authorization rows are removed with the users, so that the next test of the class can create its own admin user without colliding with the
|
||||
/// admin role permissions of the previous one.
|
||||
/// </remarks>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
await dbContext.Set<RolePermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserPermissionEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserRoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.MediaConsumptionRecords.ExecuteDeleteAsync();
|
||||
await dbContext.Libraries.ExecuteDeleteAsync();
|
||||
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<RoleEntity>().ExecuteDeleteAsync();
|
||||
await dbContext.Set<PermissionEntity>().ExecuteDeleteAsync();
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+540
@@ -0,0 +1,540 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedCountedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedUncountedStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackInProgressStartedOnUtc = new(2026, 3, 4, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStoppedFivePagesStartedOnUtc = new(2026, 2, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStoppedSixPagesStartedOnUtc = new(2026, 2, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookInProgressStartedOnUtc = new(2026, 2, 4, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenHistoryExists_ShouldApplyCountingRulesAndBreakdownByMediaKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(359.999, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(4, summary.CountedSessionCount);
|
||||
Assert.Equal(2, summary.CompletedSessionCount);
|
||||
Assert.Equal(2, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
|
||||
Assert.Equal(2, summary.MediaKindSummaries.Count);
|
||||
|
||||
MediaKindConsumptionSummaryResponse trackSummary = summary.MediaKindSummaries[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(79.999, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, trackSummary.CountedSessionCount);
|
||||
Assert.Equal(1, trackSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, trackSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, trackSummary.CompletionRate, 6);
|
||||
|
||||
MediaKindConsumptionSummaryResponse bookSummary = summary.MediaKindSummaries[1];
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
Assert.Equal(280d, bookSummary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, bookSummary.CountedSessionCount);
|
||||
Assert.Equal(1, bookSummary.CompletedSessionCount);
|
||||
Assert.Equal(1, bookSummary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, bookSummary.CompletionRate, 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenStartDateCarriesAZoneDesignator_ShouldUseTheDescribedUtcInstant()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00Z");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(79.999, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(280d, summary!.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenHistoryIsEmpty_ShouldReturnZeroedTotalsAndEmptyBreakdown()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(0d, summary.TotalConsumedDurationInSeconds);
|
||||
Assert.Equal(0, summary.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(0d, summary.CompletionRate);
|
||||
Assert.Empty(summary.MediaKindSummaries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenInProgressSessionReachedTheThreshold_ShouldCountItTowardsStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
// The media kind rule counts a session when it completed or when it reached the threshold of its kind, which an in-progress session can do.
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackCompletedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(1, summary!.CountedSessionCount);
|
||||
Assert.Equal(0, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(30d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(1, trackSummary.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetConsumptionStatistics_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-date")] // a textual value that is not a date
|
||||
[InlineData("2026-13-45T99:99:99")] // a value with out of range components
|
||||
public async Task GetConsumptionStatistics_WhenADateBoundIsNotAValidDate_ShouldReturnValidationProblem(string invalidDate)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics";
|
||||
string url = $"{path}?fromUtc={Uri.EscapeDataString(invalidDate)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a music library and an ebook library owned by <paramref name="userId"/>, with one track and one book history.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library and the ebook library.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedCountedStartedOnUtc, 30_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedUncountedStartedOnUtc, 29_999, 0);
|
||||
// An in-progress session counts only through the threshold branch of its media kind rule, so it is kept below both thresholds here.
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.InProgress, s_trackInProgressStartedOnUtc, 10_000, 0);
|
||||
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedFivePagesStartedOnUtc, 60_000, 5);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Stopped, s_bookStoppedSixPagesStartedOnUtc, 90_000, 6);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.InProgress, s_bookInProgressStartedOnUtc, 30_000, 2);
|
||||
|
||||
return (musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserConsumptionStatisticsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_completedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_stoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserConsumptionStatisticsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_stoppedStartedOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(userId, summary!.UserId);
|
||||
Assert.Equal(90d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(2, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(1, summary.StoppedSessionCount);
|
||||
Assert.Equal(0.5, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse trackSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.MusicTrack, trackSummary.MediaKind);
|
||||
Assert.Equal(90d, trackSummary.TotalConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.False(problemDetails!.ContainsKey("mediaKindSummaries"));
|
||||
Assert.False(problemDetails.ContainsKey("countedSessionCount"));
|
||||
Assert.False(problemDetails.ContainsKey("totalConsumedDurationInSeconds"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenAdminNamesAnotherUser_ShouldReturnThatUsersStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, Guid.NewGuid(), ConsumptionStatus.Completed, s_completedStartedOnUtc, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
ConsumptionSummaryResponse? summary = await DeserializeAsync<ConsumptionSummaryResponse>(response);
|
||||
Assert.NotNull(summary);
|
||||
Assert.Equal(targetUserId, summary!.UserId);
|
||||
Assert.Equal(300d, summary.TotalConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, summary.CountedSessionCount);
|
||||
Assert.Equal(1, summary.CompletedSessionCount);
|
||||
Assert.Equal(0, summary.StoppedSessionCount);
|
||||
Assert.Equal(1d, summary.CompletionRate, 6);
|
||||
MediaKindConsumptionSummaryResponse bookSummary = Assert.Single(summary.MediaKindSummaries);
|
||||
Assert.Equal(MediaKind.Book, bookSummary.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserConsumptionStatistics_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+550
@@ -0,0 +1,550 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackAFirstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackASecondStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackAThirdStartedOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBFirstStartedOnUtc = new(2026, 3, 2, 8, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackBSecondStartedOnUtc = new(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookFirstStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookSecondStartedOnUtc = new(2026, 2, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenHistoryExists_ShouldOrderByCountedSessionsThenDurationThenLastConsumed()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(3, history.Data.Count);
|
||||
|
||||
Assert.Equal(new[] { trackAId, trackBId, bookCId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
|
||||
ConsumedItemResponse mostConsumed = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, mostConsumed.MediaKind);
|
||||
Assert.Equal(musicLibraryId, mostConsumed.LibraryId);
|
||||
Assert.True(mostConsumed.IsAvailable);
|
||||
Assert.Equal("Track A", mostConsumed.Title);
|
||||
Assert.Equal("Album A", mostConsumed.CollectionTitle);
|
||||
Assert.Equal("Artist A", mostConsumed.CreatorName);
|
||||
Assert.Null(mostConsumed.CoverPath);
|
||||
Assert.Equal(s_trackAThirdStartedOnUtc, mostConsumed.LastConsumedOnUtc);
|
||||
Assert.Equal(3, mostConsumed.CountedSessionCount);
|
||||
Assert.Equal(3, mostConsumed.CompletedSessionCount);
|
||||
Assert.Equal(30d, mostConsumed.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse second = history.Data[1];
|
||||
Assert.Equal(trackBId, second.MediaItemId);
|
||||
Assert.Equal(2, second.CountedSessionCount);
|
||||
Assert.Equal(200d, second.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBSecondStartedOnUtc, second.LastConsumedOnUtc);
|
||||
|
||||
ConsumedItemResponse third = history.Data[2];
|
||||
Assert.Equal(bookCId, third.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, third.LibraryId);
|
||||
Assert.Equal(2, third.CountedSessionCount);
|
||||
Assert.Equal(200d, third.ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_bookSecondStartedOnUtc, third.LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, Guid bookLibraryId, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.All(history!.Data, item => Assert.Equal(MediaKind.MusicTrack, item.MediaKind));
|
||||
Assert.Equal(new[] { trackAId, trackBId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-02T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(new[] { trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(2, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(20d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackAId, Guid trackBId, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T08:30:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/most-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the February book sessions and drops the later track sessions, which changes both the counts and the order.
|
||||
Assert.Equal(new[] { bookCId, trackBId, trackAId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(200d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
Assert.Equal(100d, history.Data[1].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackBFirstStartedOnUtc, history.Data[1].LastConsumedOnUtc);
|
||||
Assert.Equal(1, history.Data[2].CountedSessionCount);
|
||||
Assert.Equal(10d, history.Data[2].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackAFirstStartedOnUtc, history.Data[2].LastConsumedOnUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, _, _, Guid bookCId) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/most-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(bookCId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetMostConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/most-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two tracks with three and two sessions and a book with two sessions, all owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library, both tracks, the ebook library, and the book.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackAId, Guid trackBId, Guid bookLibraryId, Guid bookCId)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackAId = await SeedTrackAsync(musicLibraryId, "Track A", "Album A", "Artist A");
|
||||
Guid trackBId = await SeedTrackAsync(musicLibraryId, "Track B", "Album B", "Artist B");
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
Guid bookCId = await SeedBookAsync(bookLibraryId, "Book C", $"Author C {Guid.NewGuid():N}");
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAFirstStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackASecondStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackAId, s_trackAThirdStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBFirstStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackBId, s_trackBSecondStartedOnUtc, 100_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookFirstStartedOnUtc, 100_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookCId, s_bookSecondStartedOnUtc, 100_000, 10);
|
||||
|
||||
return (musicLibraryId, trackAId, trackBId, bookLibraryId, bookCId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+473
@@ -0,0 +1,473 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserMostConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_firstStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_secondStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserMostConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid mostConsumedBookId = await SeedBookAsync(libraryId, "Most Consumed Book", "Author One");
|
||||
Guid lessConsumedBookId = await SeedBookAsync(libraryId, "Less Consumed Book", "Author Two");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, mostConsumedBookId, s_secondStartedOnUtc, 120_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, lessConsumedBookId, s_secondStartedOnUtc, 300_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/most-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.Count);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(new[] { mostConsumedBookId, lessConsumedBookId }, history.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(2, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(240d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal("Most Consumed Book", history.Data[0].Title);
|
||||
Assert.Equal("Author One", history.Data[0].CreatorName);
|
||||
Assert.Equal(1, history.Data[1].CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, s_firstStartedOnUtc, 120_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersMostConsumedItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, s_firstStartedOnUtc, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/most-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/most-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserMostConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/most-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc,
|
||||
endedOnUtc: startedOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+639
@@ -0,0 +1,639 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackFirstStartedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackFirstLastActivityOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondStartedOnUtc = new(2026, 3, 2, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackSecondLastActivityOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdStartedOnUtc = new(2026, 3, 3, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackThirdLastActivityOnUtc = new(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookStartedOnUtc = new(2026, 2, 28, 19, 50, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookLastActivityOnUtc = new(2026, 2, 28, 20, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_missingItemLastActivityOnUtc = new(2026, 3, 5, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenCalledForCurrentUser_ShouldReturnAggregatedHistory()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=1&perPage=10");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(1, history!.CurrentPage);
|
||||
Assert.Equal(10, history.PerPage);
|
||||
Assert.Equal(2, history.Count);
|
||||
Assert.Equal(1, history.NumberOfPages);
|
||||
Assert.Equal(2, history.Data.Count);
|
||||
|
||||
ConsumedItemResponse track = history.Data[0];
|
||||
Assert.Equal(MediaKind.MusicTrack, track.MediaKind);
|
||||
Assert.Equal(trackId, track.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, track.LibraryId);
|
||||
Assert.True(track.IsAvailable);
|
||||
Assert.Equal("Bohemian Rhapsody", track.Title);
|
||||
Assert.Equal("A Night at the Opera", track.CollectionTitle);
|
||||
Assert.Equal("Queen", track.CreatorName);
|
||||
Assert.Null(track.CoverPath);
|
||||
Assert.Equal(s_trackThirdLastActivityOnUtc, track.LastConsumedOnUtc);
|
||||
Assert.Equal(2, track.CountedSessionCount);
|
||||
Assert.Equal(1, track.CompletedSessionCount);
|
||||
Assert.Equal(100d, track.ConsumedDurationInSeconds);
|
||||
|
||||
ConsumedItemResponse book = history.Data[1];
|
||||
Assert.Equal(MediaKind.Book, book.MediaKind);
|
||||
Assert.Equal(bookId, book.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, book.LibraryId);
|
||||
Assert.True(book.IsAvailable);
|
||||
Assert.Equal("The Fellowship of the Ring", book.Title);
|
||||
Assert.Equal(string.Empty, book.CollectionTitle);
|
||||
Assert.Equal(authorName, book.CreatorName);
|
||||
Assert.Null(book.CoverPath);
|
||||
Assert.Equal(s_bookLastActivityOnUtc, book.LastConsumedOnUtc);
|
||||
Assert.Equal(1, book.CountedSessionCount);
|
||||
Assert.Equal(1, book.CompletedSessionCount);
|
||||
Assert.Equal(500d, book.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, Guid bookLibraryId, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(bookLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKind()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(musicLibraryId, item.LibraryId);
|
||||
Assert.Equal(1, history.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, _, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(trackId, item.MediaItemId);
|
||||
Assert.Equal(2, item.CountedSessionCount);
|
||||
Assert.Equal(100d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid trackId, _, Guid bookId, _) = await SeedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-03-02T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
// The end of the range keeps the book session of February and drops only the third track session of March, which started after it.
|
||||
Assert.Equal(new[] { trackId, bookId }, history!.Data.Select(item => item.MediaItemId).ToArray());
|
||||
Assert.Equal(1, history.Data[0].CountedSessionCount);
|
||||
Assert.Equal(1, history.Data[0].CompletedSessionCount);
|
||||
Assert.Equal(55d, history.Data[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal(s_trackSecondLastActivityOnUtc, history.Data[0].LastConsumedOnUtc);
|
||||
Assert.Equal(500d, history.Data[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenPaginationIsRequested_ShouldReturnRequestedPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid newestBookId = await SeedBookAsync(libraryId, "Newest Book");
|
||||
Guid middleBookId = await SeedBookAsync(libraryId, "Middle Book");
|
||||
Guid oldestBookId = await SeedBookAsync(libraryId, "Oldest Book");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, newestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 3, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 3, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, middleBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, oldestBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed?currentPage=2&perPage=2");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Equal(2, history!.CurrentPage);
|
||||
Assert.Equal(2, history.PerPage);
|
||||
Assert.Equal(3, history.Count);
|
||||
Assert.Equal(2, history.NumberOfPages);
|
||||
ConsumedItemResponse item = Assert.Single(history.Data);
|
||||
Assert.Equal(oldestBookId, item.MediaItemId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenAnotherUserHasHistory_ShouldReturnOnlyCurrentUserItems()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid ownLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Own Library");
|
||||
Guid ownBookId = await SeedBookAsync(ownLibraryId, "Own Book");
|
||||
await SeedRecordAsync(userId, ownLibraryId, MediaKind.Book, ownBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 1, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, new DateTime(2026, 3, 2, 9, 0, 0, DateTimeKind.Utc), new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc), 60_000, 10);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(ownBookId, item.MediaItemId);
|
||||
Assert.Equal("Own Book", item.Title);
|
||||
Assert.DoesNotContain(history.Data, candidate => candidate.Title == "Other User Secret Book");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenMediaItemNoLongerExists_ShouldReturnCountsWithBlankDisplayData()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid missingTrackId = Guid.NewGuid();
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, missingTrackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_missingItemLastActivityOnUtc, 30_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(MediaKind.MusicTrack, item.MediaKind);
|
||||
Assert.Equal(missingTrackId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.False(item.IsAvailable);
|
||||
Assert.Equal(string.Empty, item.Title);
|
||||
Assert.Equal(string.Empty, item.CollectionTitle);
|
||||
Assert.Equal(string.Empty, item.CreatorName);
|
||||
Assert.Null(item.CoverPath);
|
||||
Assert.Equal(s_missingItemLastActivityOnUtc, item.LastConsumedOnUtc);
|
||||
Assert.Equal(1, item.CountedSessionCount);
|
||||
Assert.Equal(1, item.CompletedSessionCount);
|
||||
Assert.Equal(30d, item.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetRecentlyConsumed_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-history/recently-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds two libraries owned by <paramref name="userId"/>, a track with three sessions, and a book with one session.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>The Ids of the music library, the track, the ebook library, and the book, and the unique name of the book author.</returns>
|
||||
private async Task<(Guid musicLibraryId, Guid trackId, Guid bookLibraryId, Guid bookId, string authorName)> SeedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// The contributor display name is unique across the whole database, so every test seeds its own spelling of the author.
|
||||
string authorName = $"J. R. R. Tolkien {Guid.NewGuid():N}";
|
||||
Guid musicLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
Guid trackId = await SeedTrackAsync(musicLibraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", []);
|
||||
Guid bookLibraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(bookLibraryId, "The Fellowship of the Ring", authorName, []);
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackFirstStartedOnUtc, s_trackFirstLastActivityOnUtc, 40_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackSecondStartedOnUtc, s_trackSecondLastActivityOnUtc, 15_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackThirdStartedOnUtc, s_trackThirdLastActivityOnUtc, 45_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookStartedOnUtc, s_bookLastActivityOnUtc, 500_000, 10);
|
||||
|
||||
return (musicLibraryId, trackId, bookLibraryId, bookId, authorName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="tagNames">The tag names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <param name="tagNames">The tag names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null, IReadOnlyList<string>? tagNames = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames ?? [])
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="lastActivityOnUtc">The date and time when the session last received activity.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
DateTime lastActivityOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.Common;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserRecentlyConsumedEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 9, 55, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly BookContributorEntityFixture _bookContributorEntityFixture = new();
|
||||
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserRecentlyConsumedEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenCurrentUserNamesTheirOwnId_ShouldReturnSameDataAsMeRoute()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.EBook, "Book Library");
|
||||
Guid bookId = await SeedBookAsync(libraryId, "The Fellowship of the Ring", "J. R. R. Tolkien");
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string query = "currentPage=1&perPage=10";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage meResponse = await _client.GetAsync($"/api/v1/users/me/consumption-history/recently-consumed?{query}");
|
||||
HttpResponseMessage userResponse = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?{query}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, meResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, userResponse.StatusCode);
|
||||
AssertCacheHeaders(userResponse);
|
||||
|
||||
PaginatedResponse<ConsumedItemResponse>? meHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(meResponse);
|
||||
PaginatedResponse<ConsumedItemResponse>? userHistory = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(userResponse);
|
||||
Assert.NotNull(meHistory);
|
||||
Assert.NotNull(userHistory);
|
||||
Assert.Equal(meHistory!.Count, userHistory!.Count);
|
||||
Assert.Equal(meHistory.CurrentPage, userHistory.CurrentPage);
|
||||
Assert.Equal(meHistory.PerPage, userHistory.PerPage);
|
||||
Assert.Equal(meHistory.NumberOfPages, userHistory.NumberOfPages);
|
||||
Assert.Equal(JsonSerializer.Serialize(meHistory.Data, _jsonOptions), JsonSerializer.Serialize(userHistory.Data, _jsonOptions));
|
||||
|
||||
ConsumedItemResponse item = Assert.Single(userHistory.Data);
|
||||
Assert.Equal(bookId, item.MediaItemId);
|
||||
Assert.Equal(libraryId, item.LibraryId);
|
||||
Assert.Equal("The Fellowship of the Ring", item.Title);
|
||||
Assert.Equal("J. R. R. Tolkien", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserHasNoHistory_ShouldReturnEmptyPage()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-history/recently-consumed?currentPage=1&perPage=50");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
Assert.Empty(history!.Data);
|
||||
Assert.Equal(1, history.CurrentPage);
|
||||
Assert.Equal(50, history.PerPage);
|
||||
Assert.Equal(0, history.Count);
|
||||
Assert.Equal(0, history.NumberOfPages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.EBook, "Other Library");
|
||||
Guid otherBookId = await SeedBookAsync(otherLibraryId, "Other User Secret Book", "Secret Author");
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.Book, otherBookId, ConsumptionStatus.Completed, 500_000, 10);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("Other User Secret Book", content);
|
||||
Assert.DoesNotContain("Secret Author", content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenAdminNamesAnotherUser_ShouldReturnThatUsersData()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target Music Library");
|
||||
Guid targetTrackId = await SeedTrackAsync(targetLibraryId, "The Show Must Go On", "Innuendo", "Queen");
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, targetTrackId, ConsumptionStatus.Completed, 60_000, 0);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-history/recently-consumed");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
PaginatedResponse<ConsumedItemResponse>? history = await DeserializeAsync<PaginatedResponse<ConsumedItemResponse>>(response);
|
||||
Assert.NotNull(history);
|
||||
ConsumedItemResponse item = Assert.Single(history!.Data);
|
||||
Assert.Equal(targetTrackId, item.MediaItemId);
|
||||
Assert.Equal(targetLibraryId, item.LibraryId);
|
||||
Assert.Equal("The Show Must Go On", item.Title);
|
||||
Assert.Equal("Innuendo", item.CollectionTitle);
|
||||
Assert.Equal("Queen", item.CreatorName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/recently-consumed";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserRecentlyConsumed_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-history/recently-consumed";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a book of <paramref name="libraryId"/>, together with an author contributor when a name is supplied.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="authorName">The name of the author of the book, or <see langword="null"/> for no contributor.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, string? authorName = null)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid? contributorId = null;
|
||||
if (authorName is not null)
|
||||
{
|
||||
contributorId = Guid.NewGuid();
|
||||
dbContext.MediaContributors.Add(_mediaContributorEntityFixture.Create(id: contributorId.Value, displayName: authorName));
|
||||
await dbContext.SaveChangesAsync();
|
||||
}
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
if (contributorId is not null)
|
||||
book.Contributors.Add(_bookContributorEntityFixture.Create(bookId: bookId, mediaContributorId: contributorId.Value, role: MediaContributorRole.Author));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_lastActivityOnUtc,
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : s_lastActivityOnUtc.AddMinutes(1),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_trackStoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_uncountedBookStartedOnUtc = new(2026, 2, 5, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenTaggedItemsWereConsumed_ShouldReturnLowercaseTagsOrderedByItemCountThenDurationThenName()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(3, tags!.Count);
|
||||
Assert.All(tags, tag => Assert.Equal(tag.Name.ToLowerInvariant(), tag.Name));
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), bookClubTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
|
||||
Assert.Equal(2, tags[0].ConsumedItemCount);
|
||||
Assert.Equal(370d, tags[0].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[1].ConsumedItemCount);
|
||||
Assert.Equal(300d, tags[1].ConsumedDurationInSeconds, 3);
|
||||
Assert.Equal(1, tags[2].ConsumedItemCount);
|
||||
Assert.Equal(70d, tags[2].ConsumedDurationInSeconds, 3);
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
Assert.NotEqual(musicLibraryId, bookLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, Guid bookLibraryId, string favouriteTag, string bookClubTag, _, string ignoredTag) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?libraryId={bookLibraryId}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
Assert.DoesNotContain(tags, tag => tag.Name == ignoredTag.ToLowerInvariant());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindTags()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags?mediaKind=MusicTrack");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, _, string rockTag, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?fromUtc={fromUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { favouriteTag.ToLowerInvariant(), rockTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(70d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
(_, _, string favouriteTag, string bookClubTag, _, _) = await SeedTaggedConsumptionScenarioAsync(userId);
|
||||
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/tags?toUtc={toUtc}");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(
|
||||
new[] { bookClubTag.ToLowerInvariant(), favouriteTag.ToLowerInvariant() },
|
||||
tags!.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
|
||||
{
|
||||
// Arrange
|
||||
_ = GetCurrentUserId();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Empty(tags!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = "/api/v1/users/me/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a number that is not a member name
|
||||
[InlineData("1")] // a number that is a defined enumeration value, which must still be rejected
|
||||
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
|
||||
public async Task GetTagConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
AssertCacheHeaders(response);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string path = "/api/v1/users/me/consumption-statistics/tags";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged track with a counted and an uncounted session, a tagged book with a counted session, and a tagged book without any counted session.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>
|
||||
/// The Ids of the music library and the ebook library, and the unique favourite, book club, rock, and ignored tag names that were seeded.
|
||||
/// </returns>
|
||||
private async Task<(Guid musicLibraryId, Guid bookLibraryId, string favouriteTag, string bookClubTag, string rockTag, string ignoredTag)> SeedTaggedConsumptionScenarioAsync(Guid userId)
|
||||
{
|
||||
// Each test seeds its own tag rows, so every name carries a unique suffix to keep the shared Tags table collision free.
|
||||
string suffix = Guid.NewGuid().ToString("N");
|
||||
string favouriteTag = $"Favourite-{suffix}";
|
||||
string bookClubTag = $"Book-Club-{suffix}";
|
||||
string rockTag = $"Rock-{suffix}";
|
||||
string ignoredTag = $"Ignored-{suffix}";
|
||||
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
|
||||
// The track and the book share a tag, so the tag rows are resolved once per name, and the whole graph is saved through one context, so the
|
||||
// shared row is inserted once instead of once per item that carries it.
|
||||
Dictionary<string, TagEntity> tags = [];
|
||||
TagEntity ResolveTag(string name)
|
||||
{
|
||||
if (!tags.TryGetValue(name, out TagEntity? tag))
|
||||
{
|
||||
tag = _tagEntityFixture.Create(name: name);
|
||||
tags[name] = tag;
|
||||
}
|
||||
return tag;
|
||||
}
|
||||
|
||||
Guid musicLibraryId = Guid.NewGuid();
|
||||
Guid bookLibraryId = Guid.NewGuid();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Guid uncountedBookId = Guid.NewGuid();
|
||||
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: musicLibraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: bookLibraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: musicLibraryId, name: "Queen", includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: musicLibraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
|
||||
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{trackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
|
||||
track.Tags.Add(ResolveTag(rockTag));
|
||||
track.Tags.Add(ResolveTag(favouriteTag));
|
||||
dbContext.Tracks.Add(track);
|
||||
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
|
||||
book.Tags.Add(ResolveTag(favouriteTag));
|
||||
book.Tags.Add(ResolveTag(bookClubTag));
|
||||
dbContext.Books.Add(book);
|
||||
|
||||
BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
|
||||
uncountedBook.Tags.Add(ResolveTag(ignoredTag));
|
||||
dbContext.Books.Add(uncountedBook);
|
||||
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
|
||||
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, trackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 10_000, 0);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 300_000, 10);
|
||||
await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, uncountedBookId, ConsumptionStatus.Stopped, s_uncountedBookStartedOnUtc, 500_000, 3);
|
||||
|
||||
return (musicLibraryId, bookLibraryId, favouriteTag, bookClubTag, rockTag, ignoredTag);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
ConsumptionStatus status,
|
||||
DateTime startedOnUtc,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: status,
|
||||
startedOnUtc: startedOnUtc,
|
||||
lastActivityOnUtc: startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserTagConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, IAsyncLifetime
|
||||
{
|
||||
private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private HttpClient _client;
|
||||
private readonly AuthenticatedLuminaApiFactory _apiFactory;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
||||
};
|
||||
private readonly LibraryEntityFixture _libraryEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly TagEntityFixture _tagEntityFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly UserEntityFixture _userEntityFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserTagConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
_client = await _apiFactory.CreateAuthenticatedClientAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
|
||||
string firstTag = $"First-{Guid.NewGuid():N}";
|
||||
string secondTag = $"Second-{Guid.NewGuid():N}";
|
||||
Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstTag, secondTag]);
|
||||
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
AssertCacheHeaders(response);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
Assert.Equal(2, tags!.Count);
|
||||
Assert.Equal(
|
||||
new[] { firstTag.ToLowerInvariant(), secondTag.ToLowerInvariant() },
|
||||
tags.Select(tag => tag.Name).ToArray());
|
||||
Assert.All(tags, tag => Assert.Equal(1, tag.ConsumedItemCount));
|
||||
Assert.All(tags, tag => Assert.Equal(60d, tag.ConsumedDurationInSeconds, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
|
||||
{
|
||||
// Arrange
|
||||
Guid otherUserId = await SeedUserAsync($"otheruser_{Guid.NewGuid()}");
|
||||
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
|
||||
string secretTag = $"Secret-{Guid.NewGuid():N}";
|
||||
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretTag]);
|
||||
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
|
||||
string url = $"/api/v1/users/{otherUserId}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertForbiddenAsync(response, url);
|
||||
AssertCacheHeaders(response);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(secretTag.ToLowerInvariant(), content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersTagStatistics()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = await SeedUserAsync($"targetuser_{Guid.NewGuid()}");
|
||||
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
|
||||
string targetTag = $"Target-{Guid.NewGuid():N}";
|
||||
Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetTag]);
|
||||
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
|
||||
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/tags");
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<TagConsumptionResponse>? tags = await DeserializeAsync<List<TagConsumptionResponse>>(response);
|
||||
Assert.NotNull(tags);
|
||||
TagConsumptionResponse tag = Assert.Single(tags!);
|
||||
Assert.Equal(targetTag.ToLowerInvariant(), tag.Name);
|
||||
Assert.Equal(1, tag.ConsumedItemCount);
|
||||
Assert.Equal(300d, tag.ConsumedDurationInSeconds, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
string url = "/api/v1/users/not-a-guid/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
|
||||
{
|
||||
// Arrange
|
||||
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
|
||||
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/tags";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnauthorizedAsync(response, url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?libraryId=not-a-guid";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string url = $"{path}?mediaKind=None";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserTagConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = GetCurrentUserId();
|
||||
string path = $"/api/v1/users/{userId}/consumption-statistics/tags";
|
||||
string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
|
||||
string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
|
||||
string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await _client.GetAsync(url);
|
||||
|
||||
// Assert
|
||||
await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library type owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="tagNames">The tag names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid artistId = Guid.NewGuid();
|
||||
Guid albumId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
|
||||
dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
track.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Tracks.Add(track);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return trackId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a tagged book of <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="tagNames">The tag names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList<string> tagNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
|
||||
foreach (string tagName in tagNames)
|
||||
book.Tags.Add(_tagEntityFixture.Create(name: tagName));
|
||||
dbContext.Books.Add(book);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return bookId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid recordId = Guid.NewGuid();
|
||||
MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
|
||||
id: recordId,
|
||||
userId: userId,
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
startedOnUtc: s_startedOnUtc,
|
||||
lastActivityOnUtc: s_startedOnUtc.AddMinutes(1),
|
||||
endedOnUtc: s_startedOnUtc.AddMinutes(2),
|
||||
consumedDurationMilliseconds: consumedDurationMilliseconds,
|
||||
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
|
||||
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
|
||||
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
|
||||
lastProgressFraction: 0,
|
||||
consecutivePagesRead: consecutivePagesRead);
|
||||
dbContext.MediaConsumptionRecords.Add(record);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return recordId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <param name="username">The username of the seeded user.</param>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync(string username)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
|
||||
dbContext.Users.Add(user);
|
||||
await dbContext.SaveChangesAsync();
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.NotNull(problemDetails["traceId"].GetString());
|
||||
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
|
||||
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
|
||||
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes API factory resources.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
await _apiFactory.RemoveTestUserAsync();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user