Implements tests for commit b2d274f609

This commit is contained in:
BinaryAlley committed 2026-10-27 17:32:37 +02:00
1 parent d185c77999
commit 5c436fc13d
17 files changed
+2261 -6

No files matched your search

@@ -96,6 +96,171 @@ public class LibraryRepositoryTests
Assert.Equal(keptLocationId, context.Entry(library.ContentLocations.Single(location => location.Path == "/media/keep")).Property<Guid>("Id").CurrentValue);
}
[Fact]
public async Task InsertAsync_WhenLibraryTracksConsumptionProgress_ShouldPersistTheTrackingAndThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-consumption-tracking-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 75, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(75, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task InsertAsync_WhenLibraryDoesNotTrackConsumptionProgress_ShouldPersistTrackingOffWithoutThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-insert-consumption-off-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
// Act
Result<Created> result = await sut.InsertAsync(library, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateAsync_WhenConsumptionSettingsAreEnabled_ShouldPersistTheTrackingAndThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-on-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 60);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(60, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateAsync_WhenConsumptionSettingsAreDisabled_ShouldPersistTrackingOffWithoutThreshold()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-off-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 80, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateAsync_WhenOnlyConsumptionSettingsChange_ShouldStampTheUpdateAudit()
{
// Arrange
using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-libraryrepo-update-consumption-audit-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
anchorConnection.Open();
Guid userId = Guid.NewGuid();
DateTime utcNow = new(2025, 1, 1, 12, 0, 0, DateTimeKind.Utc);
using LuminaDbContext context = CreateAuditedContext(anchorConnection, userId, utcNow);
LibraryRepository sut = new(context);
context.Users.Add(_userEntityFixture.Create(id: userId));
LibraryEntity library = _libraryEntityFixture.Create(userId: userId, shouldTrackConsumptionProgress: false, completionThresholdPercentage: null, contentLocations: []);
context.Libraries.Add(library);
await context.SaveChangesAsync();
LibraryEntity incoming = _libraryEntityFixture.Create(
id: library.Id,
userId: userId,
title: library.Title,
coverImage: library.CoverImage,
libraryType: library.LibraryType,
contentLocations: [],
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 55);
// Act
Result<Updated> result = await sut.UpdateAsync(incoming, CancellationToken.None);
await context.SaveChangesAsync();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? storedLibrary = await context.Libraries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(55, storedLibrary.CompletionThresholdPercentage);
Assert.Equal(utcNow, storedLibrary.UpdatedOnUtc);
Assert.Equal(userId, storedLibrary.UpdatedBy);
}
/// <summary>
/// Creates a real SQLite backed context with the auditing interceptor attached, so that audit columns behave exactly like in production.
/// </summary>
@@ -124,6 +124,269 @@ public class AddLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFacto
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task AddLibrary_WhenConsumptionSettingsAreSupplied_ShouldPersistAndReturnThem()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "Tracked Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 90
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldTrackConsumptionProgress);
Assert.Equal(90, library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(90, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task AddLibrary_WhenConsumptionSettingsAreOmitted_ShouldUseTheLibraryTypeDefaults()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "Default Consumption Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldTrackConsumptionProgress);
Assert.Equal(100, library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(100, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task AddLibrary_WhenLibraryTypeDoesNotTrackConsumptionByDefault_ShouldStoreTrackingOffWithoutThreshold()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "Music Library",
libraryType: "Music",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.Equal(LibraryType.Music, library!.LibraryType);
Assert.False(library.ShouldTrackConsumptionProgress);
Assert.Null(library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task AddLibrary_WhenProgressTrackingIsExplicitlyDisabled_ShouldStoreTrackingOffWithoutThreshold()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "Untracked Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.False(library!.ShouldTrackConsumptionProgress);
Assert.Null(library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == library.Id);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task AddLibrary_WhenThresholdIsAboveOneHundred_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Above Range Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 101
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenThresholdIsBelowZero_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Below Range Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: -1
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
[Fact]
public async Task AddLibrary_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldReturnValidationProblemAndNotPersist()
{
// Arrange
string title = "Disabled Tracking Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(candidate => candidate.Title == title));
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the add library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
@@ -135,18 +135,299 @@ public class UpdateLibraryEndpointTests : IClassFixture<AuthenticatedLuminaApiFa
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
}
[Fact]
public async Task UpdateLibrary_WhenConsumptionSettingsAreSupplied_ShouldPersistAndReturnThem()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldTrackConsumptionProgress);
Assert.Equal(70, library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenConsumptionSettingsAreOmitted_ShouldKeepTheStoredSettings()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldTrackConsumptionProgress);
Assert.Equal(70, library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenProgressTrackingIsDisabled_ShouldClearTheStoredThreshold()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.False(library!.ShouldTrackConsumptionProgress);
Assert.Null(library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.False(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Null(storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenTrackingIsEnabledWithoutThreshold_ShouldUseTheLibraryTypeDefault()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: false, completionThresholdPercentage: null);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
LibraryResponse? library = await response.Content.ReadFromJsonAsync<LibraryResponse>(_jsonOptions);
Assert.NotNull(library);
Assert.True(library!.ShouldTrackConsumptionProgress);
Assert.Equal(100, library.CompletionThresholdPercentage);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(100, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenThresholdIsAboveOneHundred_ShouldReturnValidationProblemAndKeepTheStoredSettings()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 101
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldReturnValidationProblemAndKeepTheStoredSettings()
{
// Arrange
Guid userId = GetCurrentUserId();
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, "Original Title", shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Updated Title",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(candidate => candidate.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedInstance">The expected instance path of the problem.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <param name="shouldTrackConsumptionProgress">Whether the seeded library tracks the consumption progress of its items.</param>
/// <param name="completionThresholdPercentage">The completion threshold percentage of the seeded library, if any.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title)
private async Task SeedLibraryAsync(
Guid libraryId,
Guid userId,
string title,
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Libraries.Add(_libraryEntityFixture.Create(
id: libraryId,
userId: userId,
title: title,
libraryType: LibraryType.EBook,
contentLocations: [],
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
completionThresholdPercentage: completionThresholdPercentage));
await dbContext.SaveChangesAsync();
}
@@ -111,4 +111,111 @@ public class AddLibraryEndpointTests : IClassFixture<LuminaApiFactory>
Assert.NotNull(storedLibrary);
Assert.Equal(maliciousTitle, storedLibrary!.Title);
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(101)] // just above the allowed range
[InlineData(int.MinValue)] // lowest possible value
[InlineData(int.MaxValue)] // highest possible value
public async Task AddLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestWithoutPersisting(int completionThresholdPercentage)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
string title = $"Out Of Range Library {completionThresholdPercentage}";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage
);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
string content = await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(library => library.Title == title));
}
[Fact]
public async Task AddLibrary_WhenThresholdIsSuppliedWithProgressTrackingDisabled_ShouldRejectTheRequestWithoutPersisting()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
string title = "Disabled Tracking Library";
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: title,
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request);
// Assert
string content = await AssertValidationProblemAsync(response, "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Assert.False(await dbContext.Libraries.AnyAsync(library => library.Title == title));
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the add library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
return content;
}
}
@@ -122,17 +122,216 @@ public class UpdateLibraryEndpointTests : IClassFixture<LuminaApiFactory>
Assert.Equal(maliciousTitle, storedLibrary!.Title);
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(101)] // just above the allowed range
[InlineData(int.MinValue)] // lowest possible value
[InlineData(int.MaxValue)] // highest possible value
public async Task UpdateLibrary_WhenThresholdIsOutsideAllowedRange_ShouldRejectTheRequestAndKeepTheStoredSettings(int completionThresholdPercentage)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
string content = await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenThresholdIsSuppliedWithProgressTrackingDisabled_ShouldRejectTheRequestAndKeepTheStoredSettings()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, userId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: userId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
string content = await AssertValidationProblemAsync(response, $"/api/v1/libraries/{libraryId}", "CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff");
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
[Fact]
public async Task UpdateLibrary_WhenNonOwnerTriesToChangeConsumptionSettings_ShouldNotApplyThem()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
Guid libraryId = Guid.NewGuid();
await SeedLibraryAsync(libraryId, ownerId, shouldTrackConsumptionProgress: true, completionThresholdPercentage: 70);
// Authenticating a second user on the same client replaces the bearer token, so the update below is sent as the non-owner.
(Guid _, string attackerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
id: libraryId,
userId: ownerId,
title: "Test Library",
libraryType: "EBook",
contentLocations: ["C:/Media"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null
);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request);
// Assert
// The update handler authorizes after loading the library and answers a non-owner with the NotAuthorized application error,
// which the shared problem mapping exposes as 403 Forbidden (ownership is a permission problem, not a missing resource).
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId);
Assert.NotNull(storedLibrary);
Assert.True(storedLibrary!.ShouldTrackConsumptionProgress);
Assert.Equal(70, storedLibrary.CompletionThresholdPercentage);
}
await _apiFactory.RemoveTestUserAsync(attackerUsername);
await _apiFactory.RemoveTestUserAsync(ownerUsername);
}
/// <summary>
/// Asserts that <paramref name="response"/> carries the standard validation problem of the update library route.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedInstance">The expected instance path of the problem.</param>
/// <param name="expectedErrorDescription">The error description expected under the validation errors.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorDescription)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
Assert.Equal("General.Validation", problemDetails["title"].GetString());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
Assert.NotNull(problemDetails["traceId"].GetString());
Assert.NotEmpty(problemDetails["traceId"].GetString()!);
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors!.Keys);
Assert.Contains(expectedErrorDescription, errors["General.Validation"]);
return content;
}
/// <summary>
/// Seeds a <see cref="LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library to seed.</param>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the library.</param>
/// <param name="shouldTrackConsumptionProgress">Whether the seeded library tracks the consumption progress of its items.</param>
/// <param name="completionThresholdPercentage">The completion threshold percentage of the seeded library, if any.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedLibraryAsync(Guid libraryId, Guid userId)
private async Task SeedLibraryAsync(
Guid libraryId,
Guid userId,
string title = "Test Library",
bool shouldTrackConsumptionProgress = false,
int? completionThresholdPercentage = null)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Libraries.Add(_libraryEntityFixture.Create(
id: libraryId,
userId: userId,
title: title,
libraryType: LibraryType.EBook,
contentLocations: [],
shouldTrackConsumptionProgress: shouldTrackConsumptionProgress,
completionThresholdPercentage: completionThresholdPercentage));
await dbContext.SaveChangesAsync();
}
}
@@ -190,4 +190,57 @@ public class AddMediaLibraryRequestMappingTests
// Assert
Assert.Null(result.PathTemplateParts);
}
[Fact]
public void ToCommand_WhenConsumptionSettingsAreSupplied_ShouldMapThem()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 75);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.ShouldTrackConsumptionProgress);
Assert.True(result.ShouldTrackConsumptionProgress.Value);
Assert.Equal(75, result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenConsumptionSettingsAreAbsent_ShouldPreserveThemAsNull()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.ShouldTrackConsumptionProgress);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProgressTrackingIsExplicitlyDisabled_ShouldPreserveTheDisabledFlagWithoutThreshold()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.ShouldTrackConsumptionProgress);
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
}
@@ -254,4 +254,145 @@ public class LibraryEntityMappingTests
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void ToResponse_WhenProgressTrackingIsEnabled_ShouldMapTrackingAndThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
LibraryResponse result = entity.ToResponse();
// Assert
Assert.True(result.ShouldTrackConsumptionProgress);
Assert.Equal(65, result.CompletionThresholdPercentage);
}
[Fact]
public void ToResponse_WhenProgressTrackingIsDisabled_ShouldMapTrackingOffWithoutThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
LibraryResponse result = entity.ToResponse();
// Assert
Assert.False(result.ShouldTrackConsumptionProgress);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToDomainEntity_WhenProgressTrackingIsEnabled_ShouldMapConsumptionSettings()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress);
Assert.True(result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue);
Assert.Equal(65, result.Value.ConsumptionSettings.CompletionThresholdPercentage.Value);
}
[Fact]
public void ToDomainEntity_WhenProgressTrackingIsEnabledWithoutThreshold_ShouldMapNoThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress);
Assert.False(result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void ToDomainEntity_WhenProgressTrackingIsDisabledButStoredThresholdExists_ShouldNotRetainThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.ConsumptionSettings.ShouldTrackConsumptionProgress);
Assert.False(result.Value.ConsumptionSettings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void ToDomainValueObject_WhenProgressTrackingIsEnabled_ShouldMapTrackingAndThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
LibraryConsumptionSettings result = entity.ToDomainValueObject();
// Assert
Assert.True(result.ShouldTrackConsumptionProgress);
Assert.True(result.CompletionThresholdPercentage.HasValue);
Assert.Equal(65, result.CompletionThresholdPercentage.Value);
}
[Fact]
public void ToDomainValueObject_WhenProgressTrackingIsDisabled_ShouldNotRetainThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Act
LibraryConsumptionSettings result = entity.ToDomainValueObject();
// Assert
Assert.False(result.ShouldTrackConsumptionProgress);
Assert.False(result.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void ToDomainValueObject_WhenProgressTrackingIsEnabledWithoutThreshold_ShouldMapNoThreshold()
{
// Arrange
LibraryEntity entity = _libraryEntityFixture.Create(
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null);
// Act
LibraryConsumptionSettings result = entity.ToDomainValueObject();
// Assert
Assert.True(result.ShouldTrackConsumptionProgress);
Assert.False(result.CompletionThresholdPercentage.HasValue);
}
}
@@ -25,6 +25,7 @@ public class LibraryMappingTests
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
[Fact]
public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly()
@@ -244,4 +245,46 @@ public class LibraryMappingTests
// Assert
Assert.Empty(result.PathTemplateParts);
}
[Fact]
public void ToRepositoryEntity_WhenProgressTrackingIsEnabled_ShouldMapTrackingAndThreshold()
{
// Arrange
LibraryConsumptionSettings consumptionSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 70);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
consumptionSettings: consumptionSettings);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
Assert.True(result.ShouldTrackConsumptionProgress);
Assert.Equal(70, result.CompletionThresholdPercentage);
}
[Fact]
public void ToRepositoryEntity_WhenProgressTrackingIsDisabled_ShouldMapTrackingOffWithoutThreshold()
{
// Arrange
LibraryConsumptionSettings consumptionSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 70);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
consumptionSettings: consumptionSettings);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
Assert.False(result.ShouldTrackConsumptionProgress);
Assert.Null(result.CompletionThresholdPercentage);
}
}
@@ -93,4 +93,57 @@ public class UpdateLibraryRequestMappingTests
// Assert
Assert.Null(result.PathTemplateParts);
}
[Fact]
public void ToCommand_WhenConsumptionSettingsAreSupplied_ShouldMapThem()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 75);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.ShouldTrackConsumptionProgress);
Assert.True(result.ShouldTrackConsumptionProgress.Value);
Assert.Equal(75, result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenConsumptionSettingsAreAbsent_ShouldPreserveThemAsNull()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.ShouldTrackConsumptionProgress);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProgressTrackingIsExplicitlyDisabled_ShouldPreserveTheDisabledFlagWithoutThreshold()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
libraryType: "Book",
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.ShouldTrackConsumptionProgress);
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
}
@@ -459,4 +459,153 @@ public class AddLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsNotSpecifiedAndLibraryTypeTracksByDefault_ShouldUseTheTypeDefaults()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.EBook),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.LibraryType == LibraryType.EBook &&
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 100),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsNotSpecifiedAndLibraryTypeDoesNotTrackByDefault_ShouldStoreTrackingOffWithoutThreshold()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Music),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.LibraryType == LibraryType.Music &&
!library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsExplicitlyEnabledOnATypeWithoutDefaultThreshold_ShouldStoreTrackingOnWithoutThreshold()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Music),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.LibraryType == LibraryType.Music &&
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenExplicitThresholdIsSuppliedWhileProgressTrackingIsEnabled_ShouldStoreTheSuppliedThreshold()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 42);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.LibraryType == LibraryType.Book &&
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 42),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsExplicitlyDisabledWithoutThreshold_ShouldStoreTrackingOffWithoutThreshold()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.LibraryType == LibraryType.Book &&
!library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsExplicitlyDisabledButThresholdIsSupplied_ShouldReturnThresholdMustBeNullError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff, result.FirstError);
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -303,4 +303,109 @@ public class AddLibraryCommandValidatorTests
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
}
[Fact]
public void Validate_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
}
[Fact]
public void Validate_WhenThresholdIsSuppliedWhileProgressTrackingIsNotSpecified_ShouldNotHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: 50);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenProgressTrackingIsDisabledWithoutThreshold_ShouldNotHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
}
@@ -600,4 +600,211 @@ public class UpdateLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConsumptionSettingsAreNotSpecified_ShouldKeepTheStoredSettings()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 80),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThresholdIsSuppliedWhileTrackingStaysEnabled_ShouldStoreTheSuppliedThreshold()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: 60);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 60),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsDisabled_ShouldDropTheStoredThreshold()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
!library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProgressTrackingIsExplicitlyDisabledButThresholdIsSupplied_ShouldReturnThresholdMustBeNullError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackingStaysEnabledWithoutThreshold_ShouldKeepTheStoredThresholdInsteadOfTheTypeDefault()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 80),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTrackingIsEnabledWithoutThresholdAndTheLibraryTypeHasNoDefault_ShouldStoreTrackingOnWithoutThreshold()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Music),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == null),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenThresholdIsSuppliedWhileEnablingTracking_ShouldStoreTheSuppliedThreshold()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Music),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.ShouldTrackConsumptionProgress &&
library.CompletionThresholdPercentage == 65),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -358,4 +358,109 @@ public class UpdateLibraryCommandValidatorTests
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: completionThresholdPercentage);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
}
[Fact]
public void Validate_WhenThresholdIsSuppliedWhileProgressTrackingIsDisabled_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 50);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
}
[Fact]
public void Validate_WhenThresholdIsSuppliedWhileProgressTrackingIsNotSpecified_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: 50);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenProgressTrackingIsDisabledWithoutThreshold_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
libraryType: nameof(LibraryType.Book),
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
}
@@ -70,8 +70,12 @@ public class LibraryConfigurationTests
Assert.Equal("TEXT", libraryTypeProperty.GetColumnType());
Assert.Equal(true, isEnabledProperty.GetDefaultValue());
Assert.Equal(true, downloadMetadataProperty.GetDefaultValue());
Assert.Equal(typeof(bool), shouldTrackConsumptionProgressProperty.ClrType);
Assert.False(shouldTrackConsumptionProgressProperty.IsNullable);
Assert.Equal(false, shouldTrackConsumptionProgressProperty.GetDefaultValue());
Assert.Equal(typeof(int?), completionThresholdPercentageProperty.ClrType);
Assert.True(completionThresholdPercentageProperty.IsNullable);
Assert.Null(completionThresholdPercentageProperty.GetDefaultValue());
}
[Fact]
@@ -103,6 +107,42 @@ public class LibraryConfigurationTests
// Assert
Assert.Equal(16, shouldTrackProperty.GetColumnOrder());
Assert.Equal(17, completionThresholdProperty.GetColumnOrder());
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackProperty.GetColumnName());
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdProperty.GetColumnName());
}
[Fact]
public void Configure_WhenApplied_ShouldMapConsumptionSettingsAsScalarProperties()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty shouldTrackConsumptionProgressProperty = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress));
IProperty completionThresholdPercentageProperty = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage));
List<INavigation> navigations = [.. entityType.GetNavigations()];
// Assert
Assert.Equal(typeof(LibraryEntity), shouldTrackConsumptionProgressProperty.DeclaringType.ClrType);
Assert.Equal(typeof(LibraryEntity), completionThresholdPercentageProperty.DeclaringType.ClrType);
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.ShouldTrackConsumptionProgress));
Assert.DoesNotContain(navigations, navigation => navigation.Name == nameof(LibraryEntity.CompletionThresholdPercentage));
}
[Fact]
public void Configure_WhenApplied_ShouldMapConsumptionSettingsToTheirOwnColumns()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
string shouldTrackConsumptionProgressColumnName = entityType.GetProperty(nameof(LibraryEntity.ShouldTrackConsumptionProgress)).GetColumnName();
string completionThresholdPercentageColumnName = entityType.GetProperty(nameof(LibraryEntity.CompletionThresholdPercentage)).GetColumnName();
// Assert
Assert.Equal(nameof(LibraryEntity.ShouldTrackConsumptionProgress), shouldTrackConsumptionProgressColumnName);
Assert.Equal(nameof(LibraryEntity.CompletionThresholdPercentage), completionThresholdPercentageColumnName);
Assert.NotEqual(shouldTrackConsumptionProgressColumnName, completionThresholdPercentageColumnName);
}
[Fact]
@@ -0,0 +1,296 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryConsumptionSettings"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryConsumptionSettingsTests
{
private readonly LibraryConsumptionSettingsFixture _libraryConsumptionSettingsFixture = new();
[Fact]
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsSupplied_ShouldRetainThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Assert
Assert.True(settings.ShouldTrackConsumptionProgress);
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(65, settings.CompletionThresholdPercentage.Value);
}
[Fact]
public void Create_WhenProgressTrackingIsEnabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
includeCompletionThreshold: false);
// Assert
Assert.True(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsSupplied_ShouldNotRetainThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Create_WhenProgressTrackingIsDisabledAndThresholdIsAbsent_ShouldHaveNoThreshold()
{
// Act
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
includeCompletionThreshold: false);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void Equals_WhenSettingsHaveSameValues_ShouldReturnTrue()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
bool areEqual = firstSettings.Equals(secondSettings);
// Assert
Assert.True(areEqual);
}
[Fact]
public void Equals_WhenProgressTrackingDiffers_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings trackingSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings notTrackingSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 65);
// Act
bool areEqual = trackingSettings.Equals(notTrackingSettings);
// Assert
Assert.False(areEqual);
}
[Fact]
public void Equals_WhenThresholdsDiffer_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 40);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 60);
// Act
bool areEqual = firstSettings.Equals(secondSettings);
// Assert
Assert.False(areEqual);
}
[Fact]
public void Equals_WhenProgressTrackingIsDisabled_ShouldIgnoreAnySuppliedThreshold()
{
// Arrange
LibraryConsumptionSettings settingsWithThreshold = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: 40);
LibraryConsumptionSettings settingsWithoutThreshold = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: false,
includeCompletionThreshold: false);
// Act
bool areEqual = settingsWithThreshold.Equals(settingsWithoutThreshold);
// Assert
Assert.False(settingsWithThreshold.CompletionThresholdPercentage.HasValue);
Assert.False(settingsWithoutThreshold.CompletionThresholdPercentage.HasValue);
Assert.True(areEqual);
}
[Fact]
public void Equals_WhenComparedWithNull_ShouldReturnFalse()
{
// Arrange
LibraryConsumptionSettings settings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
bool areEqual = settings.Equals((object?)null);
// Assert
Assert.False(areEqual);
}
[Fact]
public void GetHashCode_WhenSettingsAreEqual_ShouldReturnSameHashCode()
{
// Arrange
LibraryConsumptionSettings firstSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
LibraryConsumptionSettings secondSettings = _libraryConsumptionSettingsFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
// Act
int firstHashCode = firstSettings.GetHashCode();
int secondHashCode = secondSettings.GetHashCode();
// Assert
Assert.Equal(firstHashCode, secondHashCode);
}
[Theory]
[InlineData(LibraryType.Book, true, 100)] // written content
[InlineData(LibraryType.EBook, true, 100)] // written content
[InlineData(LibraryType.ComicBook, true, 100)] // written content
[InlineData(LibraryType.Magazine, true, 100)] // written content
[InlineData(LibraryType.Newspaper, true, 100)] // written content
[InlineData(LibraryType.Manga, true, 100)] // written content
[InlineData(LibraryType.GraphicNovel, true, 100)] // written content
[InlineData(LibraryType.AcademicPaper, true, 100)] // written content
[InlineData(LibraryType.SheetMusic, true, 100)] // written content
[InlineData(LibraryType.TvShow, true, 90)] // video
[InlineData(LibraryType.Movie, true, 90)] // video
[InlineData(LibraryType.Documentary, true, 90)] // video
[InlineData(LibraryType.Anime, true, 90)] // video
[InlineData(LibraryType.ConcertVideo, true, 90)] // video
[InlineData(LibraryType.TutorialVideo, true, 90)] // video
[InlineData(LibraryType.HomeVideo, true, 90)] // video
[InlineData(LibraryType.YouTubeVideo, true, 90)] // video
[InlineData(LibraryType.MusicVideo, true, 90)] // video
[InlineData(LibraryType.LiveRecordingVideo, true, 90)] // video
[InlineData(LibraryType.InterviewVideo, true, 90)] // video
[InlineData(LibraryType.CoverSongVideo, true, 90)] // video
[InlineData(LibraryType.Audiobook, true, 95)] // audiobooks and podcasts
[InlineData(LibraryType.PodcastAudio, true, 95)] // audiobooks and podcasts
[InlineData(LibraryType.PodcastVideo, true, 95)] // audiobooks and podcasts
[InlineData(LibraryType.Music, false, null)] // music audio and photos
[InlineData(LibraryType.Remix, false, null)] // music audio and photos
[InlineData(LibraryType.SoundEffect, false, null)] // music audio and photos
[InlineData(LibraryType.LiveRecordingAudio, false, null)] // music audio and photos
[InlineData(LibraryType.InterviewAudio, false, null)] // music audio and photos
[InlineData(LibraryType.CoverSongAudio, false, null)] // music audio and photos
[InlineData(LibraryType.Photo, false, null)] // music audio and photos
[InlineData(LibraryType.Playlist, false, null)] // library types that are not media libraries
[InlineData(LibraryType.Collection, false, null)] // library types that are not media libraries
[InlineData(LibraryType.Subtitles, false, null)] // library types that are not media libraries
[InlineData(LibraryType.Lyrics, false, null)] // library types that are not media libraries
[InlineData(LibraryType.Other, false, null)] // library types that are not media libraries
public void CreateDefault_WhenLibraryTypeIsKnown_ShouldReturnTheTypeDefaults(
LibraryType libraryType,
bool expectedShouldTrackConsumptionProgress,
int? expectedCompletionThresholdPercentage)
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(libraryType);
// Assert
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
if (expectedCompletionThresholdPercentage is null)
Assert.False(settings.CompletionThresholdPercentage.HasValue);
else
{
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
}
}
[Fact]
public void CreateDefault_WhenLibraryTypeIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((LibraryType)999);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Theory]
[InlineData(MediaKind.None, false, null)] // no media kind
[InlineData(MediaKind.MusicTrack, false, null)] // music tracks
[InlineData(MediaKind.PodcastEpisode, true, 95)] // audiobooks and podcast episodes
[InlineData(MediaKind.Audiobook, true, 95)] // audiobooks and podcast episodes
[InlineData(MediaKind.Movie, true, 90)] // video
[InlineData(MediaKind.TvEpisode, true, 90)] // video
[InlineData(MediaKind.Book, true, 100)] // written content
[InlineData(MediaKind.Photo, false, null)] // photos
[InlineData(MediaKind.Video, true, 90)] // video
public void CreateDefault_WhenMediaKindIsKnown_ShouldReturnTheKindDefaults(
MediaKind mediaKind,
bool expectedShouldTrackConsumptionProgress,
int? expectedCompletionThresholdPercentage)
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(mediaKind);
// Assert
Assert.Equal(expectedShouldTrackConsumptionProgress, settings.ShouldTrackConsumptionProgress);
if (expectedCompletionThresholdPercentage is null)
Assert.False(settings.CompletionThresholdPercentage.HasValue);
else
{
Assert.True(settings.CompletionThresholdPercentage.HasValue);
Assert.Equal(expectedCompletionThresholdPercentage.Value, settings.CompletionThresholdPercentage.Value);
}
}
[Fact]
public void CreateDefault_WhenMediaKindIsNotClassified_ShouldReturnTrackingOffWithoutThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault((MediaKind)999);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
[Fact]
public void CreateDefault_WhenReturnedSettingsAreTrackingOff_ShouldNotRetainAThreshold()
{
// Act
LibraryConsumptionSettings settings = LibraryConsumptionSettings.CreateDefault(LibraryType.Music);
// Assert
Assert.False(settings.ShouldTrackConsumptionProgress);
Assert.False(settings.CompletionThresholdPercentage.HasValue);
}
}
@@ -86,7 +86,9 @@ public class AddLibraryEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldSendAddLibraryCommandToSender()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create();
AddLibraryRequest request = _addLibraryRequestFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddLibraryCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryResponseFixture.Create()));
@@ -111,6 +113,28 @@ public class AddLibraryEndpointTests
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenConsumptionSettingsAreAbsent_ShouldSendNullConsumptionSettings()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<AddLibraryCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<AddLibraryCommand>(command =>
command.ShouldTrackConsumptionProgress == null &&
command.CompletionThresholdPercentage == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
@@ -86,7 +86,9 @@ public class UpdateLibraryEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateLibraryCommandToSender()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create();
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 65);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateLibraryCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId)));
@@ -113,6 +115,28 @@ public class UpdateLibraryEndpointTests
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenConsumptionSettingsAreAbsent_ShouldSendNullConsumptionSettings()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(
shouldTrackConsumptionProgress: null,
completionThresholdPercentage: null);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateLibraryCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateLibraryCommand>(command =>
command.ShouldTrackConsumptionProgress == null &&
command.CompletionThresholdPercentage == null),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{