Updates the provider configuration and ownership tests

Covers the provider and reader choices saved with a library, the reconciliation and stale configuration deletion in the provider store, the library type lookups, the ownership and permission checks for update and delete, and the validator behavior for enum names.
This commit is contained in:
BinaryAlley committed 2026-11-03 10:00:00 +02:00
1 parent 48ad8692af
commit 64e5163229
127 files changed
+5541 -5296

No files matched your search

@@ -56,6 +56,7 @@ public class AddLibraryCommandHandlerTests
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -76,14 +77,14 @@ public class AddLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<AddLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully
// Default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<AddLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
@@ -107,8 +108,8 @@ public class AddLibraryCommandHandlerTests
Assert.False(result.IsFailure);
Assert.Equal(persistedLibrary.Id, result.Value.Id);
await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(
Arg.Any<Guid>(), Arg.Is<LibraryType>(libraryType => libraryType == Enum.Parse<LibraryType>(command.LibraryType)), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Is<LibraryType>(libraryType => libraryType == Enum.Parse<LibraryType>(command.LibraryType!)), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Is(true), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
@@ -157,12 +158,40 @@ public class AddLibraryCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenProviderChoicesAreMade_ShouldConfigureProvidersWithTheChoices()
{
// Arrange
LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)];
LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)];
LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()];
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
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 _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
Arg.Any<Guid>(),
Enum.Parse<LibraryType>(command.LibraryType!),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == metadataProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == artworkProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == bookReaders),
Arg.Is(true),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to seed provider configurations"));
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to configure provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -7,6 +7,7 @@ using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -22,6 +23,7 @@ public class AddLibraryCommandValidatorTests
private readonly AddLibraryCommandValidator _validator = new();
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
@@ -37,12 +39,14 @@ public class AddLibraryCommandValidatorTests
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Fact]
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError()
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = "UnknownLibraryType" };
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
@@ -65,6 +69,36 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("book")] // The casing of the name does not matter.
[InlineData("eBook")] // The casing of the name does not matter.
public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create();
command = command with { LibraryType = "0" }; // Book
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError()
{
@@ -220,9 +254,9 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
[InlineData(null)] // An absent kind.
[InlineData("")] // An empty kind.
[InlineData(" ")] // A whitespace kind.
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
@@ -237,9 +271,9 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
[InlineData(null)] // An absent representation.
[InlineData("")] // An empty representation.
[InlineData(" ")] // A whitespace representation.
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
@@ -305,8 +339,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(int.MinValue)] // The lowest possible value.
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -323,8 +357,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MaxValue)] // The highest possible value.
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -341,8 +375,8 @@ public class AddLibraryCommandValidatorTests
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
[InlineData(0)] // The lowest allowed boundary.
[InlineData(100)] // The highest allowed boundary.
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -408,4 +442,116 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
AddLibraryCommand command = _addLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(
metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
}
@@ -14,6 +14,7 @@ using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.DeleteLi
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -60,10 +61,12 @@ public class DeleteLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<DeleteLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, the ownership policy allows the deletion, and the provider configurations are removed successfully
// Default stubs: the current user is authenticated, the ownership policy allows the deletion, the user has the manage permission, and the provider configurations are removed successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(true);
_mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockLibraryRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
@@ -170,6 +173,49 @@ public class DeleteLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionDeletesTheLibraryOfAnotherUser_ShouldDeleteIt()
{
// Arrange
DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError()
{
@@ -58,6 +58,7 @@ public class UpdateLibraryCommandHandlerTests
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -78,15 +79,17 @@ public class UpdateLibraryCommandHandlerTests
_mockValidator = Substitute.For<IValidator<UpdateLibraryCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated, has the manage permission, the cover image is a valid image, and the provider configurations are reconciled successfully
// Default stubs: the current user is authenticated, owns the library, has the manage permission, the cover image is a valid image, and the provider configurations are configured successfully.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<UpdateLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
@@ -99,8 +102,8 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -112,8 +115,8 @@ public class UpdateLibraryCommandHandlerTests
Assert.False(result.IsFailure);
Assert.Equal(existingLibrary.Id, result.Value.Id);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync(
command.Id, Arg.Is<LibraryType>(libraryType => libraryType == commandLibraryType), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
command.Id, Arg.Is<LibraryType>(libraryType => libraryType == commandLibraryType), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Is(true), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockDomainEventsQueue.Received(1).Enqueue(Arg.Any<LibrarySavedDomainEvent>());
}
@@ -127,7 +130,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 50);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
shouldTrackConsumptionProgress: false);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -152,7 +155,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
@@ -171,12 +174,34 @@ public class UpdateLibraryCommandHandlerTests
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeIsUnchanged_ShouldNotReconcileProviderConfigurations()
public async Task HandleAsync_WhenAnAdminUpdatesTheLibraryOfAnotherUser_ShouldKeepTheStoredOwner()
{
// Arrange
Guid ownerId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: ownerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// 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.UserId == ownerId),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeIsUnchangedAndNoProviderChoicesAreMade_ShouldNotConfigureProviders()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -185,21 +210,144 @@ public class UpdateLibraryCommandHandlerTests
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving()
public async Task HandleAsync_WhenProviderChoicesAreMadeAndLibraryTypeIsUnchanged_ShouldConfigureProvidersWithTheChoices()
{
// Arrange
LibraryProviderSelectionDto[] metadataProviders = [.. _libraryProviderSelectionDtoFixture.CreateMany(2)];
LibraryProviderSelectionDto[] artworkProviders = [_libraryProviderSelectionDtoFixture.Create(isEnabled: false)];
LibraryProviderSelectionDto[] bookReaders = [_libraryProviderSelectionDtoFixture.Create()];
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockProviderConfigurationStore.Received(1).ConfigureProvidersAsync(
command.Id,
commandLibraryType,
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == metadataProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == artworkProviders),
Arg.Is<IReadOnlyList<LibraryProviderSelectionDto>?>(selections => selections == bookReaders),
Arg.Is(false),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionUpdatesTheLibrary_ShouldReturnNotAuthorizedWithoutChangingAnything(bool hasProviderChoices)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: hasProviderChoices ? [_libraryProviderSelectionDtoFixture.Create()] : null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
existingLibrary.LibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenANonOwnerWithTheManagePermissionChangesTheLibraryType_ShouldReturnNotAuthorizedWithoutChangingTheConfigurations()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(libraryType: nameof(LibraryType.Book));
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid(), libraryType: LibraryType.Music);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockProviderConfigurationStore.DidNotReceive().ConfigureProvidersAsync(
Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenTheOwnerLacksTheManagePermission_ShouldReturnNotAuthorizedWithoutChangingAnything()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAnAdminWithoutTheManagePermissionUpdatesTheLibraryOfAnotherUser_ShouldUpdateIt()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: Guid.NewGuid());
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(true);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfiguringProvidersFails_ShouldReturnErrorWithoutSaving()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryType commandLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book;
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to reconcile provider configurations"));
_mockProviderConfigurationStore.ConfigureProvidersAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<IReadOnlyList<LibraryProviderSelectionDto>?>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to configure provider configurations"));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
@@ -215,7 +363,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = null };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -234,7 +382,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = "C:/Users/user/cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -257,7 +405,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = "C:/Users/user/cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -279,7 +427,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = " " };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -294,12 +442,39 @@ public class UpdateLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserLacksManagePermissionAndCoverImageIsNew_ShouldNotProbeCoverImage()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { CoverImage = @"\\server\share\cover.jpg" };
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = null;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockEnvironmentContext.FileTypeService.DidNotReceive()
.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
existingLibrary.CoverImage = command.CoverImage;
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -333,6 +508,28 @@ public class UpdateLibraryCommandHandlerTests
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenLibraryDoesNotExistAndUserLacksPermission_ShouldReturnNotFoundWithoutAuthorizing()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result<LibraryEntity?>.Success(null));
_mockAuthorizationService.IsInRoleAsync(_userId, AuthorizationRoles.ADMIN, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationService.HasPermissionAsync(_userId, AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError()
{
@@ -355,7 +552,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>())
@@ -395,7 +592,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
command = command with { ContentLocations = [""] };
@@ -415,7 +612,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(command.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
_mockLibraryRepository.UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>())
@@ -434,7 +631,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary), Error.Failure(description: "Failed to retrieve updated library"));
@@ -450,7 +647,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary), Result<LibraryEntity?>.Success(null));
@@ -486,7 +683,7 @@ public class UpdateLibraryCommandHandlerTests
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
@@ -524,7 +721,7 @@ public class UpdateLibraryCommandHandlerTests
representation: "{0}",
isOptional: false);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
@@ -562,7 +759,7 @@ public class UpdateLibraryCommandHandlerTests
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
@@ -585,7 +782,7 @@ public class UpdateLibraryCommandHandlerTests
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
@@ -611,7 +808,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -641,7 +838,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 60);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -671,7 +868,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -701,7 +898,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 50);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -728,7 +925,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Book,
shouldTrackConsumptionProgress: true,
completionThresholdPercentage: 80);
@@ -758,7 +955,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
@@ -788,7 +985,7 @@ public class UpdateLibraryCommandHandlerTests
completionThresholdPercentage: 65);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(
id: command.Id,
userId: command.OwnerId,
userId: _userId,
libraryType: LibraryType.Music,
shouldTrackConsumptionProgress: false,
completionThresholdPercentage: null);
@@ -23,6 +23,7 @@ public class UpdateLibraryCommandValidatorTests
private readonly UpdateLibraryCommandValidator _validator = new();
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
@@ -51,33 +52,6 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenOwnerIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { OwnerId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Users.UserIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenOwnerIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Users.UserIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
{
@@ -92,12 +66,14 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Fact]
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError()
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = "UnknownLibraryType" };
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
@@ -120,6 +96,36 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("book")] // The casing of the name does not matter.
[InlineData("eBook")] // The casing of the name does not matter.
public void Validate_WhenLibraryTypeDiffersInCasing_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = libraryType };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenLibraryTypeIsTheNumericValueOfADefinedMember_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create();
command = command with { LibraryType = "0" }; // Book
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Fact]
public void Validate_WhenContentLocationsIsNull_ShouldHaveValidationError()
{
@@ -275,9 +281,9 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
[InlineData(null)] // An absent kind.
[InlineData("")] // An empty kind.
[InlineData(" ")] // A whitespace kind.
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
@@ -292,9 +298,9 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
[InlineData(null)] // An absent representation.
[InlineData("")] // An empty representation.
[InlineData(" ")] // A whitespace representation.
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
@@ -360,8 +366,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(-1)] // just below the allowed range
[InlineData(int.MinValue)] // the lowest possible value
[InlineData(-1)] // Just below the allowed range.
[InlineData(int.MinValue)] // The lowest possible value.
public void Validate_WhenThresholdIsBelowZero_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -378,8 +384,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(101)] // just above the allowed range
[InlineData(int.MaxValue)] // the highest possible value
[InlineData(101)] // Just above the allowed range.
[InlineData(int.MaxValue)] // The highest possible value.
public void Validate_WhenThresholdIsAboveOneHundred_ShouldHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -396,8 +402,8 @@ public class UpdateLibraryCommandValidatorTests
}
[Theory]
[InlineData(0)] // the lowest allowed boundary
[InlineData(100)] // the highest allowed boundary
[InlineData(0)] // The lowest allowed boundary.
[InlineData(100)] // The highest allowed boundary.
public void Validate_WhenThresholdIsAtAnAllowedBoundary_ShouldNotHaveValidationError(int completionThresholdPercentage)
{
// Arrange
@@ -463,4 +469,116 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeNullWhenProgressTrackingIsOff);
result.ShouldNotHaveValidationError(Errors.Library.CompletionThresholdPercentageMustBeBetweenZeroAndOneHundred);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenMetadataProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenArtworkProviderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(artworkProviders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenBookReaderPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: Guid.Empty)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenBookReaderPluginIdsAreDuplicated_ShouldHaveValidationError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(bookReaders: [_libraryProviderSelectionDtoFixture.Create(pluginId: pluginId), _libraryProviderSelectionDtoFixture.Create(pluginId: pluginId, isEnabled: false)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreValid_ShouldNotHaveProviderValidationErrors()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(
metadataProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
artworkProviders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)],
bookReaders: [.. _libraryProviderSelectionDtoFixture.CreateMany(2)]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
[Fact]
public void Validate_WhenProviderChoicesAreNotProvided_ShouldNotHaveProviderValidationErrors()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsMustBeUnique);
}
}
@@ -51,9 +51,10 @@ public class GetLibraryPathTemplatePartsQueryHandlerTests
}
[Theory]
[InlineData("")] // an absent library type
[InlineData(" ")] // a whitespace library type
[InlineData("NotARealLibraryType")] // an unknown library type
[InlineData("")] // An absent library type.
[InlineData(" ")] // A whitespace library type.
[InlineData("NotARealLibraryType")] // An unknown library type.
[InlineData("999")] // A number that is not a defined library type.
public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType)
{
// Arrange