Implements tests for commit 00d7eff777

Covers genre consumption and delete-item-history across application, contracts, API, and Web. Changes the new string-bound request pipelines to return validation problems instead of 500 for malformed values.
This commit is contained in:
BinaryAlley committed 2026-10-28 12:27:34 +02:00
1 parent 968061e89a
commit 1afb078efc
91 files changed
+14499 -50

No files matched your search

@@ -0,0 +1,425 @@
#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.DeleteConsumptionItemHistory;
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.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains integration tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteConsumptionItemHistoryEndpointTests : 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
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenItemHasRecords_ShouldDeleteOnlyTheMatchingRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid otherLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Other User Library");
Guid mediaItemId = Guid.NewGuid();
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
Guid otherItemRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
Guid movedLibraryRecordId = await SeedConsumptionRecordAsync(userId, otherLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
Guid otherKindRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.Book, mediaItemId, 60_000);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Owner Library");
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
await AssertRecordsArePreservedAsync(otherItemRecordId, movedLibraryRecordId, otherKindRecordId, otherUserRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalled_ShouldReturnEmptyDeletedBody()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
using JsonDocument document = JsonDocument.Parse(content);
Assert.Equal(JsonValueKind.Object, document.RootElement.ValueKind);
Assert.Empty(document.RootElement.EnumerateObject());
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenItemHasNoRecords_ShouldSucceedWithoutSideEffects()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
await AssertRecordsArePreservedAsync(existingRecordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
await AssertRecordsAreDeletedAsync(recordId);
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
AssertCacheHeaders(secondResponse);
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
{
// Arrange
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(path);
// Assert
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
AssertCacheHeaders(response);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.Empty}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(path);
// Assert
await AssertUnprocessableEntityAsync(response, path, "MediaItemIdCannotBeEmpty");
AssertCacheHeaders(response);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenLibraryIdIsEmpty_ShouldReturnValidationProblem()
{
// Arrange
string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.Empty}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(path);
// Assert
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
AssertCacheHeaders(response);
}
[Fact]
public async Task DeleteConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{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="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="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedConsumptionRecordAsync(
Guid userId,
Guid libraryId,
MediaKind mediaKind,
Guid mediaItemId,
long consumedDurationMilliseconds)
{
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_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
lastProgressFraction: 0.5,
consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 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();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
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 AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the 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>
/// Removes every user created by the test, together with the libraries it owns.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (string username in _seededUsernames)
{
UserEntity? user = dbContext.Users
.Include(candidate => candidate.Libraries)
.FirstOrDefault(candidate => candidate.Username == username);
if (user is null)
continue;
dbContext.Libraries.RemoveRange(user.Libraries);
dbContext.Users.Remove(user);
}
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,456 @@
#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.DeleteConsumptionItemHistory;
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.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
/// <summary>
/// Contains integration tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteUserConsumptionItemHistoryEndpointTests : 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
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeleteUserConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenCurrentUserNamesThemselves_ShouldDeleteTheItemRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid mediaItemId = Guid.NewGuid();
Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
{
// Arrange
_ = GetCurrentUserId();
Guid otherUserId = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
Guid mediaItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/{otherUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
await AssertForbiddenAsync(response, url);
AssertCacheHeaders(response);
await AssertRecordsArePreservedAsync(otherUserRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersItemRecords()
{
// Arrange
_ = GetCurrentUserId();
Guid targetUserId = await SeedOtherUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target User Library");
Guid mediaItemId = Guid.NewGuid();
Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/{targetUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
try
{
// Act
HttpResponseMessage response = await adminClient.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
await AssertRecordsAreDeletedAsync(targetRecordId);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotOwnTheItem_ShouldSucceedAndPreserveThatUsersRecords()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
Guid otherUserId = await SeedOtherUserAsync();
Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
Guid mediaItemId = Guid.NewGuid();
Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
await AssertRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
Guid mediaItemId = Guid.NewGuid();
Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
// Act
HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
await AssertRecordsAreDeletedAsync(recordId);
HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
// Assert
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
AssertCacheHeaders(secondResponse);
await AssertRecordsAreDeletedAsync(recordId);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
{
// Arrange
string path = $"/api/v1/users/not-a-guid/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(path);
// Assert
await AssertUnprocessableEntityAsync(response, path, "TargetUserIdIsInvalid");
AssertCacheHeaders(response);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
string path = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
// Act
HttpResponseMessage response = await _client.DeleteAsync(path);
// Assert
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
AssertCacheHeaders(response);
}
[Fact]
public async Task DeleteUserConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{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="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="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
/// <returns>The Id of the seeded record.</returns>
private async Task<Guid> SeedConsumptionRecordAsync(
Guid userId,
Guid libraryId,
MediaKind mediaKind,
Guid mediaItemId,
long consumedDurationMilliseconds)
{
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_lastActivityOnUtc,
endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
consumedDurationMilliseconds: consumedDurationMilliseconds,
lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
lastProgressFraction: 0.5,
consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 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();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
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 AssertRecordsAreDeletedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
// has run, instead of assuming that it already has.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
if (storedRecords.Count == 0)
return;
await Task.Delay(100);
}
Assert.Empty(storedRecords);
}
/// <summary>
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
/// </summary>
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<MediaConsumptionRecordEntity> storedRecords = [];
// The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
// completion has run, instead of trusting the state observed right after the response.
for (int attempt = 0; attempt < 20; attempt++)
{
storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
.Where(record => recordIds.Contains(record.Id))
.ToListAsync();
Assert.Equal(recordIds.Length, storedRecords.Count);
await Task.Delay(100);
}
Assert.Equal(recordIds.Length, storedRecords.Count);
}
/// <summary>
/// Asserts that the 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>
/// Removes every user created by the test, together with the libraries it owns.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (string username in _seededUsernames)
{
UserEntity? user = dbContext.Users
.Include(candidate => candidate.Libraries)
.FirstOrDefault(candidate => candidate.Username == username);
if (user is null)
continue;
dbContext.Libraries.RemoveRange(user.Libraries);
dbContext.Users.Remove(user);
}
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,524 @@
#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.GetGenreConsumption;
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.GetGenreConsumption;
/// <summary>
/// Contains integration tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetGenreConsumptionEndpointTests : 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 GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
}
[Fact]
public async Task GetGenreConsumption_WhenGenreBearingItemsWereConsumed_ShouldReturnLowercaseGenresOrderedByItemCountThenDurationThenName()
{
// Arrange
Guid userId = GetCurrentUserId();
(Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(3, genres!.Count);
Assert.All(genres, genre => Assert.Equal(genre.Name.ToLowerInvariant(), genre.Name));
Assert.Equal(
new[] { favouriteGenre.ToLowerInvariant(), rockGenre.ToLowerInvariant(), bookClubGenre.ToLowerInvariant() },
genres.Select(genre => genre.Name).ToArray());
Assert.Equal(2, genres[0].ConsumedItemCount);
Assert.Equal(360d, genres[0].ConsumedDurationInSeconds, 3);
Assert.Equal(2, genres[1].ConsumedItemCount);
Assert.Equal(90d, genres[1].ConsumedDurationInSeconds, 3);
Assert.Equal(1, genres[2].ConsumedItemCount);
Assert.Equal(300d, genres[2].ConsumedDurationInSeconds, 3);
Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
Assert.NotEqual(musicLibraryId, bookLibraryId);
}
[Fact]
public async Task GetGenreConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryGenres()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, Guid bookLibraryId, _, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?libraryId={bookLibraryId}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(
new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
genres!.Select(genre => genre.Name).ToArray());
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
}
[Fact]
public async Task GetGenreConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindGenres()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?mediaKind={nameof(MediaKind.MusicTrack)}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(
new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
genres!.Select(genre => genre.Name).ToArray());
Assert.Equal(2, genres[0].ConsumedItemCount);
Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
Assert.Equal(1, genres[1].ConsumedItemCount);
Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
}
[Fact]
public async Task GetGenreConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?fromUtc={fromUtc}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(
new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
genres!.Select(genre => genre.Name).ToArray());
Assert.Equal(2, genres[0].ConsumedItemCount);
Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
Assert.Equal(1, genres[1].ConsumedItemCount);
Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
}
[Fact]
public async Task GetGenreConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
{
// Arrange
Guid userId = GetCurrentUserId();
(_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?toUtc={toUtc}");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(
new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
genres!.Select(genre => genre.Name).ToArray());
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
Assert.DoesNotContain(genres, genre => genre.Name == rockGenre.ToLowerInvariant());
}
[Fact]
public async Task GetGenreConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
{
// Arrange
_ = GetCurrentUserId();
// Act
HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Empty(genres!);
}
[Fact]
public async Task GetGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = "/api/v1/users/me/consumption-statistics/genres";
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
{
// Arrange
string path = "/api/v1/users/me/consumption-statistics/genres";
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 GetGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
{
// Arrange
string path = "/api/v1/users/me/consumption-statistics/genres";
string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
AssertCacheHeaders(response);
}
[Theory]
[InlineData("999")] // a number that is not a member name
[InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
public async Task GetGenreConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
{
// Arrange
string path = "/api/v1/users/me/consumption-statistics/genres";
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 GetGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
{
// Arrange
string path = "/api/v1/users/me/consumption-statistics/genres";
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");
AssertCacheHeaders(response);
}
/// <summary>
/// Seeds a track and a book in two libraries of <paramref name="userId"/>, with counted and uncounted sessions.
/// </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 rock, favourite, book club, and ignored genre names that were seeded.
/// </returns>
private async Task<(Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre)> SeedGenreConsumptionScenarioAsync(Guid userId)
{
// Each test seeds its own genre rows, so every name carries a unique suffix to keep the shared Genres table collision free.
string suffix = Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();
string rockGenre = $"Rock-{suffix}";
string favouriteGenre = $"Favourite-{suffix}";
string bookClubGenre = $"Book-Club-{suffix}";
string ignoredGenre = $"Ignored-{suffix}";
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// The track and the book share a genre, so the genre rows are resolved once per name, and the whole graph is saved through one context.
Dictionary<string, GenreEntity> genres = [];
GenreEntity ResolveGenre(string name)
{
if (!genres.TryGetValue(name, out GenreEntity? genre))
{
genre = _genreEntityFixture.Create(name: name);
genres[name] = genre;
}
return genre;
}
Guid musicLibraryId = Guid.NewGuid();
Guid bookLibraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid firstTrackId = Guid.NewGuid();
Guid secondTrackId = 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 firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{firstTrackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
firstTrack.Genres.Add(ResolveGenre(rockGenre));
firstTrack.Genres.Add(ResolveGenre(favouriteGenre));
dbContext.Tracks.Add(firstTrack);
TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{secondTrackId:N}.flac", title: "Love of My Life", includeMetadata: false);
secondTrack.Genres.Add(ResolveGenre(rockGenre));
dbContext.Tracks.Add(secondTrack);
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
book.Genres.Add(ResolveGenre(favouriteGenre));
book.Genres.Add(ResolveGenre(bookClubGenre));
dbContext.Books.Add(book);
BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
uncountedBook.Genres.Add(ResolveGenre(ignoredGenre));
dbContext.Books.Add(uncountedBook);
await dbContext.SaveChangesAsync();
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, firstTrackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, secondTrackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 30_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, rockGenre, favouriteGenre, bookClubGenre, ignoredGenre);
}
/// <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>
/// Removes every user created by the test, together with the libraries it owns.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (string username in _seededUsernames)
{
UserEntity? user = dbContext.Users
.Include(candidate => candidate.Libraries)
.FirstOrDefault(candidate => candidate.Username == username);
if (user is null)
continue;
dbContext.Libraries.RemoveRange(user.Libraries);
dbContext.Users.Remove(user);
}
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,485 @@
#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.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.GetGenreConsumption;
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.GetGenreConsumption;
/// <summary>
/// Contains integration tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetUserGenreConsumptionEndpointTests : 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 GenreEntityFixture _genreEntityFixture = new();
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
private readonly UserEntityFixture _userEntityFixture = new();
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetUserGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
}
[Fact]
public async Task GetUserGenreConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirGenreStatistics()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
string suffix = Guid.NewGuid().ToString("N")[..8];
string firstGenre = $"First-{suffix}";
string secondGenre = $"Second-{suffix}";
Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstGenre, secondGenre]);
await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/genres");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
AssertCacheHeaders(response);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
Assert.Equal(2, genres!.Count);
Assert.Equal(
new[] { firstGenre.ToLowerInvariant(), secondGenre.ToLowerInvariant() },
genres.Select(genre => genre.Name).ToArray());
Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
Assert.All(genres, genre => Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3));
}
[Fact]
public async Task GetUserGenreConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
{
// Arrange
Guid otherUserId = await SeedUserAsync();
Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
string secretGenre = $"Secret-{Guid.NewGuid().ToString("N")[..8]}";
Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretGenre]);
await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
string url = $"/api/v1/users/{otherUserId}/consumption-statistics/genres";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertForbiddenAsync(response, url);
AssertCacheHeaders(response);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain(secretGenre, content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetUserGenreConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersGenreStatistics()
{
// Arrange
_ = GetCurrentUserId();
Guid targetUserId = await SeedUserAsync();
Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
string targetGenre = $"Target-{Guid.NewGuid().ToString("N")[..8]}";
Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetGenre]);
await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
_seededUsernames.Add(_apiFactory.TestUsername!);
try
{
// Act
HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/genres");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
List<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(response);
Assert.NotNull(genres);
GenreConsumptionResponse genre = Assert.Single(genres!);
Assert.Equal(targetGenre.ToLowerInvariant(), genre.Name);
Assert.Equal(1, genre.ConsumedItemCount);
Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3);
}
finally
{
adminClient.Dispose();
}
}
[Fact]
public async Task GetUserGenreConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
{
// Arrange
string url = "/api/v1/users/not-a-guid/consumption-statistics/genres";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
}
[Fact]
public async Task GetUserGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
{
// Arrange
HttpClient unauthenticatedClient = _apiFactory.CreateClient();
string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/genres";
// Act
HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
// Assert
await AssertUnauthorizedAsync(response, url);
}
[Fact]
public async Task GetUserGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
string url = $"{path}?libraryId=not-a-guid";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
}
[Fact]
public async Task GetUserGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
}
[Fact]
public async Task GetUserGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
{
// Arrange
Guid userId = GetCurrentUserId();
string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
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 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 genre-bearing 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="genreNames">The genre 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> genreNames)
{
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 genreName in genreNames)
track.Genres.Add(_genreEntityFixture.Create(name: genreName));
dbContext.Tracks.Add(track);
await dbContext.SaveChangesAsync();
return trackId;
}
/// <summary>
/// Seeds a genre-bearing 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="genreNames">The genre 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> genreNames)
{
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 genreName in genreNames)
book.Genres.Add(_genreEntityFixture.Create(name: genreName));
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>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = Guid.NewGuid();
string username = $"otheruser_{Guid.NewGuid()}";
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
await dbContext.SaveChangesAsync();
_seededUsernames.Add(username);
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>
/// Removes every user created by the test, together with the libraries it owns.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
foreach (string username in _seededUsernames)
{
UserEntity? user = dbContext.Users
.Include(candidate => candidate.Libraries)
.FirstOrDefault(candidate => candidate.Username == username);
if (user is null)
continue;
dbContext.Libraries.RemoveRange(user.Libraries);
dbContext.Users.Remove(user);
}
await dbContext.SaveChangesAsync();
}
}