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

@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -245,4 +249,85 @@ public class AddMediaLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
{
// Arrange
LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
}
[Fact]
public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.MetadataProviders);
Assert.Null(result.ArtworkProviders);
Assert.Null(result.BookReaders);
}
[Fact]
public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
Assert.Null(result.MetadataProviders![0].IsEnabled);
Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
}
[Fact]
public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [null]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
Assert.Null(part.Kind);
Assert.Null(part.Representation);
Assert.False(part.IsOptional);
}
[Fact]
public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
{
// Arrange
LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
AddLibraryRequest request = _addLibraryRequestFixture.Create(metadataProviders: [choice]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
Assert.Equal(choice.PluginId, mappedChoice.PluginId);
Assert.Null(mappedChoice.IsEnabled);
}
}
@@ -1,10 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -16,6 +19,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class UpdateLibraryRequestMappingTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryProviderSelectionRequestFixture _libraryProviderSelectionRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
@@ -148,4 +152,85 @@ public class UpdateLibraryRequestMappingTests
Assert.False(result.ShouldTrackConsumptionProgress.Value);
Assert.Null(result.CompletionThresholdPercentage);
}
[Fact]
public void ToCommand_WhenProviderChoicesAreProvided_ShouldMapThemInOrder()
{
// Arrange
LibraryProviderSelectionRequest[] metadataProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true), _libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] artworkProviders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: false)];
LibraryProviderSelectionRequest[] bookReaders = [_libraryProviderSelectionRequestFixture.Create(isEnabled: true)];
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: metadataProviders, artworkProviders: artworkProviders, bookReaders: bookReaders);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(metadataProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.MetadataProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(artworkProviders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.ArtworkProviders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
Assert.Equal(bookReaders.Select(selection => (selection.PluginId, selection.IsEnabled)), result.BookReaders!.Select(selection => (selection.PluginId, selection.IsEnabled)));
}
[Fact]
public void ToCommand_WhenProviderChoicesAreNotProvided_ShouldMapThemAsNull()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: null, artworkProviders: null, bookReaders: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.MetadataProviders);
Assert.Null(result.ArtworkProviders);
Assert.Null(result.BookReaders);
}
[Fact]
public void ToCommand_WhenAProviderChoiceIsNull_ShouldMapItToAChoiceWithoutPluginId()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [null], artworkProviders: [null], bookReaders: [null]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Equal(Guid.Empty, Assert.Single(result.MetadataProviders!).PluginId);
Assert.Null(result.MetadataProviders![0].IsEnabled);
Assert.Equal(Guid.Empty, Assert.Single(result.ArtworkProviders!).PluginId);
Assert.Equal(Guid.Empty, Assert.Single(result.BookReaders!).PluginId);
}
[Fact]
public void ToCommand_WhenAPathTemplatePartIsNull_ShouldMapItToAPartWithoutKind()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [null]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
LibraryPathTemplatePartDto part = Assert.Single(result.PathTemplateParts!);
Assert.Null(part.Kind);
Assert.Null(part.Representation);
Assert.False(part.IsOptional);
}
[Fact]
public void ToCommand_WhenAProviderChoiceHasNoEnabledState_ShouldMapTheStateAsNull()
{
// Arrange
LibraryProviderSelectionRequest choice = _libraryProviderSelectionRequestFixture.Create(includeIsEnabled: false);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(metadataProviders: [choice]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
LibraryProviderSelectionDto mappedChoice = Assert.Single(result.MetadataProviders!);
Assert.Equal(choice.PluginId, mappedChoice.PluginId);
Assert.Null(mappedChoice.IsEnabled);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersRequestMappingTests
{
private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeArtworkProvidersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersRequestMappingTests
{
private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeBookReadersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersRequestMappingTests
{
private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music");
// Act
GetLibraryTypeMetadataProvidersQuery result = request.ToQuery();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryType, result.LibraryType);
}
}
@@ -1,32 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersRequestMappingTests
{
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
// Act
ReorderLibraryArtworkProvidersCommand result = request.ToCommand();
// Assert
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginIds, result.PluginIds);
}
}
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersRequestMappingTests
{
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(Guid.NewGuid(), [Guid.NewGuid(), Guid.NewGuid()]);
// Act
ReorderLibraryMetadataProvidersCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginIds, result.PluginIds);
}
}
@@ -1,33 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledRequestMappingTests
{
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(isEnabled: true);
// Act
SetLibraryArtworkProviderEnabledCommand result = request.ToCommand();
// Assert
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -1,34 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledRequestMappingTests
{
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
// Act
SetLibraryBookReaderEnabledCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -1,35 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledRequestMappingTests
{
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(Guid.NewGuid(), Guid.NewGuid(), true);
// Act
SetLibraryMetadataProviderEnabledCommand result = request.ToCommand();
// Assert
Assert.NotNull(result);
Assert.Equal(request.LibraryId, result.LibraryId);
Assert.Equal(request.PluginId, result.PluginId);
Assert.Equal(request.IsEnabled, result.IsEnabled);
}
}
@@ -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
@@ -1,184 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<ReorderLibraryArtworkProvidersCommand> _mockValidator;
private readonly ReorderLibraryArtworkProvidersCommandHandler _sut;
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersCommandHandlerTests"/> class.
/// </summary>
public ReorderLibraryArtworkProvidersCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<ReorderLibraryArtworkProvidersCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<ReorderLibraryArtworkProvidersCommand>())
.Returns([]);
_sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity firstProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryArtworkProviderConfigurationEntity secondProvider = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity> { firstProvider, secondProvider });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity configuration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
Guid unknownPluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity> { configuration });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<ReorderLibraryArtworkProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get configurations"));
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,104 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersCommandValidatorTests
{
private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new();
private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { PluginIds = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
}
[Fact]
public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
command = command with { PluginIds = [] };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,144 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<ReorderLibraryMetadataProvidersCommand> _mockValidator;
private readonly ReorderLibraryMetadataProvidersCommandHandler _sut;
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandlerTests"/> class.
/// </summary>
public ReorderLibraryMetadataProvidersCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>())
.Returns([]);
_sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntity firstProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryMetadataProviderConfigurationEntity secondProvider = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryMetadataProviderConfigurationEntity> { firstProvider, secondProvider });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,104 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersCommandValidatorTests
{
private readonly ReorderLibraryMetadataProvidersCommandValidator _validator = new();
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
command = command with { PluginIds = null! };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
}
[Fact]
public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
command = command with { PluginIds = [] };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
ReorderLibraryMetadataProvidersCommand command = _reorderLibraryMetadataProvidersCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,243 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<SetLibraryArtworkProviderEnabledCommand> _mockValidator;
private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut;
private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Fixture for generating <see cref="LibraryArtworkProviderConfigurationEntity"/> test data.
/// </summary>
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryArtworkProviderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<SetLibraryArtworkProviderEnabledCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryArtworkProviderEnabledCommand>())
.Returns([]);
_sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 1),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>
{
_libraryArtworkProviderConfigurationEntityFixture.Create(
libraryId: libraryId,
pluginId: Guid.NewGuid(),
rank: 3,
isEnabled: true)
});
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => !configuration.IsEnabled && configuration.Rank == 4),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(
libraryId: Guid.NewGuid(),
pluginId: Guid.NewGuid(),
rank: 2,
isEnabled: false);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any<CancellationToken>())
.Returns(existingConfiguration);
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 2),
Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<SetLibraryArtworkProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get configuration"));
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryArtworkProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryArtworkProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to upsert configuration"));
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,89 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledCommandValidatorTests
{
private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new();
private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
command = command with { PluginId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,210 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockLibraryBookReaderConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IBookReaderEnablementCache _mockEnablementCache;
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _mockValidator;
private readonly SetLibraryBookReaderEnabledCommandHandler _sut;
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryBookReaderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryBookReaderConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockLibraryBookReaderConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockEnablementCache = Substitute.For<IBookReaderEnablementCache>();
_mockValidator = Substitute.For<IValidator<SetLibraryBookReaderEnabledCommand>>();
_userId = Guid.NewGuid();
// Default stubs: the current user is authenticated and the library ownership policy allows access.
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryBookReaderEnabledCommand>()).Returns([]);
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_sut = new SetLibraryBookReaderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockEnablementCache, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldInsertNewConfigurationAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration =>
configuration.LibraryId == command.LibraryId &&
configuration.PluginId == command.PluginId &&
configuration.IsEnabled == command.IsEnabled),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledStateAndPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(isEnabled: true);
LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(
libraryId: command.LibraryId,
pluginId: command.PluginId,
isEnabled: false);
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(existingConfiguration));
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.True(existingConfiguration.IsEnabled);
await _mockLibraryBookReaderConfigurationRepository.Received(1).UpsertAsync(existingConfiguration, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).Invalidate(command.LibraryId, command.PluginId);
}
[Fact]
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockValidator.Validate(Arg.Any<SetLibraryBookReaderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenGetConfigurationFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to get configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockLibraryBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
[Fact]
public async Task HandleAsync_WhenUpsertFails_ShouldReturnErrorAndNotPersist()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
Error error = Error.Failure(description: "Failed to upsert configuration");
_mockLibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
_mockLibraryBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().Invalidate(Arg.Any<Guid>(), Arg.Any<Guid>());
}
}
@@ -1,62 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledCommandValidatorTests
{
private readonly SetLibraryBookReaderEnabledCommandValidator _validator = new();
private readonly SetLibraryBookReaderEnabledCommandFixture _setLibraryBookReaderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(libraryId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create(pluginId: Guid.Empty);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryBookReaderEnabledCommand command = _setLibraryBookReaderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
}
@@ -1,172 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledCommandHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<SetLibraryMetadataProviderEnabledCommand> _mockValidator;
private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut;
private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Fixture for generating <see cref="LibraryMetadataProviderConfigurationEntity"/> test data.
/// </summary>
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledCommandHandlerTests"/> class.
/// </summary>
public SetLibraryMetadataProviderEnabledCommandHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>())
.Returns([]);
_sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any<CancellationToken>())
.Returns((LibraryMetadataProviderConfigurationEntity?)null);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryMetadataProviderConfigurationEntity>());
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 1),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(
libraryId: Guid.NewGuid(),
pluginId: Guid.NewGuid(),
rank: 2,
isEnabled: false);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any<CancellationToken>())
.Returns(existingConfiguration);
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.IsEnabled && configuration.Rank == 2),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,89 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledCommandValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledCommandValidatorTests
{
private readonly SetLibraryMetadataProviderEnabledCommandValidator _validator = new();
private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create();
command = command with { LibraryId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create();
command = command with { PluginId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
// Arrange
SetLibraryMetadataProviderEnabledCommand command = _setLibraryMetadataProviderEnabledCommandFixture.Create();
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -0,0 +1,184 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore;
private readonly IValidator<GetLibraryTypeArtworkProvidersQuery> _mockValidator;
private readonly GetLibraryTypeArtworkProvidersQueryHandler _sut;
private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly PaginatedResultDtoFixture<PluginEntity> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersQueryHandlerTests"/> class.
/// </summary>
public GetLibraryTypeArtworkProvidersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<GetLibraryTypeArtworkProvidersQuery>>();
// Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected.
_mockValidator.Validate(Arg.Any<GetLibraryTypeArtworkProvidersQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(Guid.NewGuid());
_mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(Arg.Any<LibraryType>()).Returns([]);
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_sut = new GetLibraryTypeArtworkProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryTypeArtworkProvidersQuery>()).Returns([Errors.Library.UnknownLibraryType]);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedArtworkProviderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]);
List<PluginEntity> plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")];
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1)));
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(new LibraryArtworkProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]);
Assert.Equal(new LibraryArtworkProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]);
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: "music");
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockProviderConfigurationStore.Received(1).GetSupportedArtworkProviderPluginIds(LibraryType.Music);
}
[Fact]
public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid unknownPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedArtworkProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryArtworkProviderResponse response = Assert.Single(result.Value);
Assert.Equal(unknownPluginId, response.PluginId);
Assert.Equal(string.Empty, response.Name);
}
[Fact]
public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create();
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create();
Error error = Error.Failure(description: "Failed to get plugins");
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersQueryValidatorTests
{
private readonly GetLibraryTypeArtworkProvidersQueryValidator _validator = new();
private readonly GetLibraryTypeArtworkProvidersQueryFixture _getLibraryTypeArtworkProvidersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create() with { LibraryType = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
[InlineData("0")] // The numeric value of a defined library type, which is not a member name.
[InlineData("")] // Empty.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeArtworkProvidersQuery query = _getLibraryTypeArtworkProvidersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
}
@@ -0,0 +1,187 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore;
private readonly IBookReaderRegistry _mockBookReaderRegistry;
private readonly IValidator<GetLibraryTypeBookReadersQuery> _mockValidator;
private readonly GetLibraryTypeBookReadersQueryHandler _sut;
private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly PaginatedResultDtoFixture<PluginEntity> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersQueryHandlerTests"/> class.
/// </summary>
public GetLibraryTypeBookReadersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockBookReaderRegistry = Substitute.For<IBookReaderRegistry>();
_mockValidator = Substitute.For<IValidator<GetLibraryTypeBookReadersQuery>>();
// Default stubs: the query is valid, the current user is authenticated, no reader supports the library type, and no plugin is detected.
_mockValidator.Validate(Arg.Any<GetLibraryTypeBookReadersQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(Guid.NewGuid());
_mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(Arg.Any<LibraryType>()).Returns([]);
_mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary<Guid, IReadOnlyList<string>>());
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_sut = new GetLibraryTypeBookReadersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockBookReaderRegistry, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryTypeBookReadersQuery>()).Returns([Errors.Library.LibraryTypeCannotBeNull]);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryTypeCannotBeNull, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedBookReaderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenReadersSupportTheLibraryType_ShouldReturnThemDisabledWithTheirNamesAndExtensions()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid epubPluginId = Guid.NewGuid();
Guid pdfPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([epubPluginId, pdfPluginId]);
List<PluginEntity> plugins = [_pluginEntityFixture.Create(pdfPluginId, "PDF Reader"), _pluginEntityFixture.Create(epubPluginId, "EPUB Reader")];
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1)));
_mockBookReaderRegistry.GetSupportedExtensionsByPluginId().Returns(new Dictionary<Guid, IReadOnlyList<string>>
{
[epubPluginId] = [".epub"],
[pdfPluginId] = [".pdf"]
});
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(epubPluginId, result.Value[0].PluginId);
Assert.Equal("EPUB Reader", result.Value[0].Name);
Assert.Equal(".epub", Assert.Single(result.Value[0].SupportedExtensions));
Assert.False(result.Value[0].IsEnabled);
Assert.Equal(pdfPluginId, result.Value[1].PluginId);
Assert.Equal("PDF Reader", result.Value[1].Name);
Assert.Equal(".pdf", Assert.Single(result.Value[1].SupportedExtensions));
Assert.False(result.Value[1].IsEnabled);
}
[Fact]
public async Task HandleAsync_WhenReaderIsMissingFromDetectedPluginsAndRegistry_ShouldUseEmptyNameAndNoExtensions()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid unknownPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedBookReaderPluginIds(LibraryType.Book).Returns([unknownPluginId]);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryBookReaderResponse response = Assert.Single(result.Value);
Assert.Equal(unknownPluginId, response.PluginId);
Assert.Equal(string.Empty, response.Name);
Assert.Empty(response.SupportedExtensions);
}
[Fact]
public async Task HandleAsync_WhenNoReaderSupportsTheLibraryType_ShouldReturnEmptyList()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: nameof(LibraryType.Music));
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
_mockProviderConfigurationStore.Received(1).GetSupportedBookReaderPluginIds(LibraryType.Music);
}
[Fact]
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create();
Error error = Error.Failure(description: "Failed to get plugins");
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<LibraryBookReaderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersQueryValidatorTests
{
private readonly GetLibraryTypeBookReadersQueryValidator _validator = new();
private readonly GetLibraryTypeBookReadersQueryFixture _getLibraryTypeBookReadersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create() with { LibraryType = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
[InlineData("0")] // The numeric value of a defined library type, which is not a member name.
[InlineData("")] // Empty.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeBookReadersQuery query = _getLibraryTypeBookReadersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
}
@@ -0,0 +1,184 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersQueryHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore;
private readonly IValidator<GetLibraryTypeMetadataProvidersQuery> _mockValidator;
private readonly GetLibraryTypeMetadataProvidersQueryHandler _sut;
private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly PaginatedResultDtoFixture<PluginEntity> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersQueryHandlerTests"/> class.
/// </summary>
public GetLibraryTypeMetadataProvidersQueryHandlerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockValidator = Substitute.For<IValidator<GetLibraryTypeMetadataProvidersQuery>>();
// Default stubs: the query is valid, the current user is authenticated, no plugin supports the library type, and no plugin is detected.
_mockValidator.Validate(Arg.Any<GetLibraryTypeMetadataProvidersQuery>()).Returns([]);
_mockCurrentUserService.UserId.Returns(Guid.NewGuid());
_mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(Arg.Any<LibraryType>()).Returns([]);
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_sut = new GetLibraryTypeMetadataProvidersQueryHandler(_mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorWithoutReadingPlugins()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryTypeMetadataProvidersQuery>()).Returns([Errors.Library.UnknownLibraryType]);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.UnknownLibraryType, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
_mockProviderConfigurationStore.DidNotReceive().GetSupportedMetadataProviderPluginIds(Arg.Any<LibraryType>());
await _mockPluginRepository.DidNotReceive().GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPluginsSupportTheLibraryType_ShouldReturnThemDisabledAndRankedInTheSupportedOrder()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([alphaPluginId, betaPluginId]);
List<PluginEntity> plugins = [_pluginEntityFixture.Create(betaPluginId, "Beta"), _pluginEntityFixture.Create(alphaPluginId, "Alpha")];
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: plugins, currentPage: 1, perPage: plugins.Count, count: plugins.Count, numberOfPages: 1)));
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(new LibraryMetadataProviderResponse(alphaPluginId, "Alpha", false, 1), result.Value[0]);
Assert.Equal(new LibraryMetadataProviderResponse(betaPluginId, "Beta", false, 2), result.Value[1]);
}
[Fact]
public async Task HandleAsync_WhenLibraryTypeCasingDiffers_ShouldStillResolveTheLibraryType()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: "music");
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockProviderConfigurationStore.Received(1).GetSupportedMetadataProviderPluginIds(LibraryType.Music);
}
[Fact]
public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: nameof(LibraryType.Book));
Guid unknownPluginId = Guid.NewGuid();
_mockProviderConfigurationStore.GetSupportedMetadataProviderPluginIds(LibraryType.Book).Returns([unknownPluginId]);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
LibraryMetadataProviderResponse response = Assert.Single(result.Value);
Assert.Equal(unknownPluginId, response.PluginId);
Assert.Equal(string.Empty, response.Name);
}
[Fact]
public async Task HandleAsync_WhenNoPluginSupportsTheLibraryType_ShouldReturnEmptyList()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create();
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create();
Error error = Error.Failure(description: "Failed to get plugins");
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersQueryValidatorTests
{
private readonly GetLibraryTypeMetadataProvidersQueryValidator _validator = new();
private readonly GetLibraryTypeMetadataProvidersQueryFixture _getLibraryTypeMetadataProvidersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create() with { LibraryType = null };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
}
[Theory]
[InlineData("UnknownLibraryType")] // Not a library type.
[InlineData("999")] // A number that is not a defined library type.
[InlineData("0")] // The numeric value of a defined library type, which is not a member name.
[InlineData("")] // Empty.
public void Validate_WhenLibraryTypeIsUnknown_ShouldHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Library.UnknownLibraryType);
}
[Theory]
[InlineData("Book")]
[InlineData("music")] // The casing of the type is ignored.
public void Validate_WhenLibraryTypeIsValid_ShouldNotHaveValidationError(string libraryType)
{
// Arrange
GetLibraryTypeMetadataProvidersQuery query = _getLibraryTypeMetadataProvidersQueryFixture.Create(libraryType: libraryType);
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.LibraryTypeCannotBeNull);
result.ShouldNotHaveValidationError(Errors.Library.UnknownLibraryType);
}
}
@@ -348,8 +348,8 @@ public class ErrorsTests
AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginSettingsCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Plugins.LibraryIdCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginIdsMustBeUnique, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginNotSupportedForLibraryType, ErrorType.Validation);
AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound);
AssertError(DomainErrors.Plugins.PluginArchiveCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Plugins.PluginFileNameCannotBeEmpty, ErrorType.Validation);
@@ -84,10 +84,13 @@ public class MediaLibraryScanProcessorJobTests : IDisposable
RegisterScan(firstScanId, LibraryScanJobStatus.Pending);
RegisterScan(secondScanId, LibraryScanJobStatus.Pending);
TaskCompletionSource<bool> releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously);
// ExecutionStarted is signaled before the callback runs, and resumes the test on another thread, so the test waits for the callback itself to record the scan
TaskCompletionSource firstScanRecorded = new(TaskCreationOptions.RunContinuationsAsynchronously);
List<Guid> startedScanIds = [];
FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ =>
{
startedScanIds.Add(firstScanId.ScanId.Value);
firstScanRecorded.SetResult();
await releaseFirstScan.Task;
});
FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ =>
@@ -102,7 +105,7 @@ public class MediaLibraryScanProcessorJobTests : IDisposable
// Act
_queue.Writer.TryWrite(firstScanId);
_queue.Writer.TryWrite(secondScanId);
await firstRootJob.ExecutionStarted.WaitAsync(s_testTimeout);
await firstScanRecorded.Task.WaitAsync(s_testTimeout);
// Assert
// The second scan must not start while the job graph of the first one is still executing.
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
@@ -19,6 +20,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
@@ -173,7 +175,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenCalled_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMade_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -198,7 +200,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -339,7 +341,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenBookReaderSupportsTheLibraryType_ShouldAddDisabledConfiguration()
public async Task EnsureProviderConfigurationsAsync_WhenABookReaderSupportsTheLibraryType_ShouldAddADisabledBookReaderConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -353,17 +355,20 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == pluginId && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
// The reader is ensured exactly once, since a second ensure in the same scope would not see the staged row and would add a duplicate.
await _mockBookReaderConfigurationRepository.Received(1).GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne()
public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderConfigurationAlreadyExists_ShouldNotAddAnotherBookReaderConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -376,7 +381,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -384,7 +389,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddConfiguration()
public async Task EnsureProviderConfigurationsAsync_WhenNoBookReaderSupportsTheLibraryType_ShouldNotAddABookReaderConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -394,7 +399,7 @@ public class MediaLibraryProviderConfigurationStoreTests
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Movie, ".epub")));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -403,7 +408,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenReaderDeclaresNoExtension_ShouldNotAddConfiguration()
public async Task EnsureProviderConfigurationsAsync_WhenTheBookReaderDeclaresNoExtension_ShouldNotAddABookReaderConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -413,7 +418,7 @@ public class MediaLibraryProviderConfigurationStoreTests
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, supportedExtension: null)));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -421,7 +426,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError()
public async Task EnsureProviderConfigurationsAsync_WhenReadingBookReaderConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -433,14 +438,14 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task EnsureBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError()
public async Task EnsureProviderConfigurationsAsync_WhenUpsertingBookReaderConfigurationFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -454,14 +459,14 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.EnsureBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenCalled_ShouldRemoveStaleAndAddTheSupportedBookReaders()
public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveStaleAndAddTheSupportedBookReaders()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -474,6 +479,7 @@ public class MediaLibraryProviderConfigurationStoreTests
(alphaPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")),
(betaPluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
LibraryBookReaderConfigurationEntity existingConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: alphaPluginId);
StubConfigurations(libraryId, [], [], []);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
@@ -482,7 +488,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -493,10 +499,11 @@ public class MediaLibraryProviderConfigurationStoreTests
Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId), Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToReadTheirConfigurations_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -504,18 +511,19 @@ public class MediaLibraryProviderConfigurationStoreTests
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
StubConfigurations(libraryId, [], [], []);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenDeletingStaleConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToDeleteStaleConfigurations_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -525,20 +533,21 @@ public class MediaLibraryProviderConfigurationStoreTests
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId);
StubConfigurations(libraryId, [], [], []);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([staleConfiguration]));
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenUpsertFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenReconcilingBookReadersFailsToUpsertAConfiguration_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -546,90 +555,21 @@ public class MediaLibraryProviderConfigurationStoreTests
IPlugin plugin = CreatePlugin(pluginId, "Reader Plugin");
_mockPluginManager.GetPlugins().Returns([plugin]);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.EBook, ".epub")));
StubConfigurations(libraryId, [], [], []);
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileBookReaderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public async Task RemoveBookReaderConfigurationsForLibraryAsync_WhenDeletionFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsForLibraryAsync(libraryId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task RemoveBookReaderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidatePlugin(pluginId);
}
[Fact]
public async Task RemoveBookReaderConfigurationsAsync_WhenDeletionFails_ShouldReturnError()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockBookReaderConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to delete the configurations"));
MediaLibraryProviderConfigurationStore sut = CreateSut();
// Act
Result<Deleted> result = await sut.RemoveBookReaderConfigurationsAsync(pluginId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidatePlugin(Arg.Any<Guid>());
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenArtworkConfigurationsAreStale_ShouldDeleteAndAddThem()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkConfigurationsAreStale_ShouldDeleteAndAddThem()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -654,7 +594,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.Updated);
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -666,7 +606,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleArtworkConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleArtworkConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -683,7 +623,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -780,7 +720,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndMetadataProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -797,7 +737,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -806,7 +746,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndArtworkProviderIsAlreadyConfigured_ShouldKeepItWithoutUpserting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -823,7 +763,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -832,7 +772,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenReadingMetadataConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingMetadataConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -844,7 +784,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -853,7 +793,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenDeletingStaleMetadataConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndDeletingStaleMetadataConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -868,14 +808,14 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to delete the configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingMetadataConfigurationFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingMetadataConfigurationFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -889,7 +829,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -897,7 +837,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenReadingArtworkConfigurationsFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndReadingArtworkConfigurationsFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -911,7 +851,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to read configurations"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -919,7 +859,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileProviderConfigurationsAsync_WhenUpsertingArtworkConfigurationFails_ShouldReturnError()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndUpsertingArtworkConfigurationFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -935,7 +875,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Error.Failure(description: "Failed to persist the configuration"));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -943,7 +883,7 @@ public class MediaLibraryProviderConfigurationStoreTests
}
[Fact]
public async Task ReconcileBookReaderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldKeepItWithoutUpserting()
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndBookReaderConfigurationAlreadyExists_ShouldKeepItWithoutUpserting()
{
// Arrange
Guid libraryId = Guid.NewGuid();
@@ -960,7 +900,7 @@ public class MediaLibraryProviderConfigurationStoreTests
.Returns(Result.From<IReadOnlyList<LibraryBookReaderConfigurationEntity>>([existingConfiguration]));
// Act
Result<Success> result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None);
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.EBook, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -1010,6 +950,505 @@ public class MediaLibraryProviderConfigurationStoreTests
await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreMade_ShouldApplyTheirOrderAndEnabledState()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null));
LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true);
StubConfigurations(libraryId, [alphaConfiguration], [], []);
LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: true), new(alphaPluginId, IsEnabled: false)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.LibraryId == libraryId && configuration.Rank == 1 && configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId && configuration.Id == alphaConfiguration.Id && configuration.Rank == 2 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenASupportedMetadataProviderIsNotNamed_ShouldKeepItsStoredStateAfterTheNamedProviders()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
Guid gammaPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta"), CreatePlugin(gammaPluginId, "Gamma")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(gammaPluginId, CreateMetadataProvider(LibraryType.Book), null, null));
LibraryMetadataProviderConfigurationEntity gammaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, gammaPluginId, 1, isEnabled: true);
StubConfigurations(libraryId, [gammaConfiguration], [], []);
LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: false)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == gammaPluginId && configuration.Rank == 2 && configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 3 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenAMetadataProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutChangingConfigurations()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] metadataProviders = [new(Guid.NewGuid(), IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError);
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenUpsertingAChosenMetadataProviderFails_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null));
StubConfigurations(libraryId, [], [], []);
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Upsert failed"));
LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid supportedPluginId = Guid.NewGuid();
Guid stalePluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(supportedPluginId, "Alpha"), CreatePlugin(stalePluginId, "Beta")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(supportedPluginId, null, CreateArtworkProvider(LibraryType.Book), null),
(stalePluginId, null, CreateArtworkProvider(LibraryType.Music), null));
LibraryArtworkProviderConfigurationEntity staleConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, stalePluginId, 1);
StubConfigurations(libraryId, [], [staleConfiguration], []);
LibraryProviderSelectionDto[] artworkProviders = [new(supportedPluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == supportedPluginId && configuration.Rank == 1 && configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryArtworkProviderConfigurationEntity>(configuration => configuration.PluginId == stalePluginId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenAnArtworkProviderChoiceNamesAnUnsupportedPlugin_ShouldReturnError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Music), null));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError);
await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMade_ShouldApplyTheirEnabledStateAndInvalidateTheEnablementCache()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid epubPluginId = Guid.NewGuid();
Guid pdfPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(pdfPluginId, "PDF Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")),
(pdfPluginId, null, null, CreateBookReader(LibraryType.Book, ".pdf")));
LibraryBookReaderConfigurationEntity pdfConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pdfPluginId, isEnabled: true);
StubConfigurations(libraryId, [], [], [pdfConfiguration]);
LibraryProviderSelectionDto[] bookReaders = [new(epubPluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == epubPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == pdfPluginId && configuration.IsEnabled),
Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreMadeAndStaleConfigurationsExist_ShouldDeleteTheStaleOnesAndApplyTheChoices()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid supportedPluginId = Guid.NewGuid();
Guid stalePluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(supportedPluginId, "EPUB Reader"), CreatePlugin(stalePluginId, "PDF Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(supportedPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")),
(stalePluginId, null, null, CreateBookReader(LibraryType.EBook, ".pdf")));
LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true);
StubConfigurations(libraryId, [], [], [staleConfiguration]);
LibraryProviderSelectionDto[] bookReaders = [new(supportedPluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == supportedPluginId && configuration.LibraryId == libraryId && configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(
Arg.Is<LibraryBookReaderConfigurationEntity>(configuration => configuration.PluginId == stalePluginId), Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public async Task ConfigureProvidersAsync_WhenABookReaderChoiceNamesAnUnsupportedPlugin_ShouldReturnErrorWithoutInvalidatingTheEnablementCache()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] bookReaders = [new(Guid.NewGuid(), IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginNotSupportedForLibraryType, result.FirstError);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenNoBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotInvalidateTheEnablementCache()
{
// Arrange
Guid libraryId = Guid.NewGuid();
MediaLibraryProviderConfigurationStore sut = CreateSut();
StubConfigurations(libraryId, [], [], []);
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenOmittedBookReadersAreReconciled_ShouldRemoveTheStaleReaderAndInvalidateTheEnablementCache()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid stalePluginId = Guid.NewGuid();
MediaLibraryProviderConfigurationStore sut = CreateSut();
LibraryBookReaderConfigurationEntity staleConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: stalePluginId, isEnabled: true);
StubConfigurations(libraryId, [], [], [staleConfiguration]);
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: true, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync(
libraryId, Arg.Is<IEnumerable<Guid>>(pluginIds => pluginIds.SequenceEqual(new[] { stalePluginId })), Arg.Any<CancellationToken>());
_mockEnablementCache.Received(1).InvalidateLibrary(libraryId);
}
[Fact]
public void GetSupportedMetadataProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder()
{
// Arrange
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
Guid unsupportedPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(unsupportedPluginId, "Gamma"), CreatePlugin(alphaPluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(unsupportedPluginId, CreateMetadataProvider(LibraryType.Music), null, null));
// Act
IReadOnlyList<Guid> result = sut.GetSupportedMetadataProviderPluginIds(LibraryType.Book);
// Assert
Assert.Equal([alphaPluginId, betaPluginId], result);
}
[Fact]
public void GetSupportedArtworkProviderPluginIds_WhenPluginsSupportTheLibraryType_ShouldReturnThemInAlphabeticalOrder()
{
// Arrange
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
Guid metadataOnlyPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(betaPluginId, "Beta"), CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(metadataOnlyPluginId, "Delta")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, null, CreateArtworkProvider(LibraryType.Music), null),
(betaPluginId, null, CreateArtworkProvider(LibraryType.Music), null),
(metadataOnlyPluginId, CreateMetadataProvider(LibraryType.Music), null, null));
// Act
IReadOnlyList<Guid> result = sut.GetSupportedArtworkProviderPluginIds(LibraryType.Music);
// Assert
Assert.Equal([alphaPluginId, betaPluginId], result);
}
[Fact]
public void GetSupportedBookReaderPluginIds_WhenAReaderDeclaresNoFileExtension_ShouldLeaveItOut()
{
// Arrange
Guid epubPluginId = Guid.NewGuid();
Guid extensionlessPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(epubPluginId, "EPUB Reader"), CreatePlugin(extensionlessPluginId, "Empty Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(epubPluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")),
(extensionlessPluginId, null, null, CreateBookReader(LibraryType.Book, null)));
// Act
IReadOnlyList<Guid> result = sut.GetSupportedBookReaderPluginIds(LibraryType.Book);
// Assert
Assert.Equal([epubPluginId], result);
}
[Fact]
public async Task ConfigureProvidersAsync_WhenOnlyBookReaderChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldLeaveTheProviderConfigurationsUntouched()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockBookReaderConfigurationRepository.Received(1).UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().DeleteByLibraryIdAndPluginIdsAsync(Arg.Any<Guid>(), Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenNoChoicesAreMadeAndOmittedKindsAreNotReconciled_ShouldNotTouchAnyConfiguration()
{
// Arrange
Guid libraryId = Guid.NewGuid();
MediaLibraryProviderConfigurationStore sut = CreateSut();
StubConfigurations(libraryId, [], [], []);
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockArtworkConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookReaderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenAChoiceHasNoEnabledState_ShouldKeepTheStoredStateAndApplyTheOrder()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid alphaPluginId = Guid.NewGuid();
Guid betaPluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(alphaPluginId, "Alpha"), CreatePlugin(betaPluginId, "Beta")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut(
(alphaPluginId, CreateMetadataProvider(LibraryType.Book), null, null),
(betaPluginId, CreateMetadataProvider(LibraryType.Book), null, null));
LibraryMetadataProviderConfigurationEntity alphaConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, alphaPluginId, 1, isEnabled: true);
StubConfigurations(libraryId, [alphaConfiguration], [], []);
LibraryProviderSelectionDto[] metadataProviders = [new(betaPluginId, IsEnabled: null), new(alphaPluginId, IsEnabled: null)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled),
Arg.Any<CancellationToken>());
await _mockMetadataConfigurationRepository.Received(1).UpsertAsync(
Arg.Is<LibraryMetadataProviderConfigurationEntity>(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 2 && configuration.IsEnabled),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenMetadataProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null, null));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] metadataProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: false)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, metadataProviders, null, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError);
await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenArtworkProviderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "Alpha")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, CreateArtworkProvider(LibraryType.Book), null));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] artworkProviders = [new(pluginId, IsEnabled: true), new(pluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, artworkProviders, null, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError);
await _mockArtworkConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ConfigureProvidersAsync_WhenBookReaderChoicesAreDuplicated_ShouldReturnErrorWithoutChangingConfigurations()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
IPlugin[] plugins = [CreatePlugin(pluginId, "EPUB Reader")];
_mockPluginManager.GetPlugins().Returns(plugins);
MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, null, null, CreateBookReader(LibraryType.Book, ".epub")));
StubConfigurations(libraryId, [], [], []);
LibraryProviderSelectionDto[] bookReaders = [new(pluginId, IsEnabled: false), new(pluginId, IsEnabled: true)];
// Act
Result<Success> result = await sut.ConfigureProvidersAsync(libraryId, LibraryType.Book, null, null, bookReaders, shouldReconcileOmittedKinds: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginIdsMustBeUnique, result.FirstError);
await _mockBookReaderConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>());
_mockEnablementCache.DidNotReceive().InvalidateLibrary(Arg.Any<Guid>());
}
/// <summary>
/// Stubs the stored configurations of a media library, and lets every write to the configuration repositories succeed.
/// </summary>
/// <param name="libraryId">The Id of the media library whose configurations are stubbed.</param>
/// <param name="metadataConfigurations">The stored metadata provider configurations.</param>
/// <param name="artworkConfigurations">The stored artwork provider configurations.</param>
/// <param name="bookReaderConfigurations">The stored book reader configurations.</param>
private void StubConfigurations(
Guid libraryId,
IReadOnlyList<LibraryMetadataProviderConfigurationEntity> metadataConfigurations,
IReadOnlyList<LibraryArtworkProviderConfigurationEntity> artworkConfigurations,
IReadOnlyList<LibraryBookReaderConfigurationEntity> bookReaderConfigurations)
{
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>()).Returns(Result.From(metadataConfigurations));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>()).Returns(Result.From(artworkConfigurations));
_mockBookReaderConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>()).Returns(Result.From(bookReaderConfigurations));
_mockMetadataConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockArtworkConfigurationRepository.UpsertAsync(Arg.Any<LibraryArtworkProviderConfigurationEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockBookReaderConfigurationRepository.UpsertAsync(Arg.Any<LibraryBookReaderConfigurationEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockArtworkConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockBookReaderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any<IEnumerable<Guid>>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
}
/// <summary>
/// Creates the store under test wired to the mocked dependencies, optionally registering the providers and book readers of the loaded plugins.
/// </summary>
@@ -1021,11 +1460,11 @@ public class MediaLibraryProviderConfigurationStoreTests
foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider, IBookReader? bookReader) in pluginServices)
{
if (metadataProvider is not null)
services.AddKeyedSingleton<IMetadataProvider>(pluginId, (_, _) => metadataProvider);
services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider);
if (artworkProvider is not null)
services.AddKeyedSingleton<IArtworkProvider>(pluginId, (_, _) => artworkProvider);
services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider);
if (bookReader is not null)
services.AddKeyedSingleton<IBookReader>(pluginId, (_, _) => bookReader);
services.AddKeyedSingleton(pluginId, (_, _) => bookReader);
}
return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider(), _mockEnablementCache);
}
@@ -77,8 +77,6 @@ public class PluginDetectionSyncJobTests
.Returns(Result.Deleted);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockProviderConfigurationStore.EnsureBookReaderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore);
@@ -229,8 +227,8 @@ public class PluginDetectionSyncJobTests
await StartAndWaitForExecutionAsync(sut);
// Assert
// A single ensure covers the metadata, artwork and book reader configurations, since a second one before the save would stage duplicates.
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).EnsureBookReaderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
@@ -239,7 +237,7 @@ public class PluginDetectionSyncJobTests
{
// Arrange
IPlugin previouslyLoadedPlugin = CreatePlugin(Guid.NewGuid(), "My Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([]); // the plugin assembly now fails to load
_mockPluginManager.GetPlugins().Returns([]); // The plugin assembly now fails to load.
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create(
@@ -44,7 +44,7 @@ public class UpdateLibraryEndpointTests
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id, userId: request.UserId);
LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id);
_mockHandler.HandleAsync(Arg.Any<UpdateLibraryCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
@@ -92,7 +92,7 @@ public class UpdateLibraryEndpointTests
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)));
.Returns(Result.From(_libraryResponseFixture.Create(id: request.Id)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -101,7 +101,6 @@ public class UpdateLibraryEndpointTests
await _mockHandler.Received(1).HandleAsync(
Arg.Is<UpdateLibraryCommand>(command =>
command.Id == request.Id &&
command.OwnerId == request.UserId &&
command.Title == request.Title &&
command.LibraryType == request.LibraryType &&
command.ContentLocations == request.ContentLocations &&
@@ -126,7 +125,7 @@ public class UpdateLibraryEndpointTests
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)));
.Returns(Result.From(_libraryResponseFixture.Create(id: request.Id)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -154,7 +153,7 @@ public class UpdateLibraryEndpointTests
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId));
return Result.From(_libraryResponseFixture.Create(id: request.Id));
}, callInfo.Arg<CancellationToken>()));
// Act
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests
{
private readonly IQueryHandler<GetLibraryTypeArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>> _mockHandler;
private readonly GetLibraryTypeArtworkProvidersEndpoint _sut;
private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeArtworkProvidersEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryTypeArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>>>();
_sut = Factory.Create<GetLibraryTypeArtworkProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithArtworkProviders()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryArtworkProviderResponse> expectedResponse = _libraryArtworkProviderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<IReadOnlyList<LibraryArtworkProviderResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<LibraryArtworkProviderResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized");
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title);
Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeArtworkProvidersQueryToSender()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryArtworkProviderResponse> response = _libraryArtworkProviderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryTypeArtworkProvidersQuery>(query => query.LibraryType == request.LibraryType),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<LibraryArtworkProviderResponse>>([]);
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeBookReaders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests
{
private readonly IQueryHandler<GetLibraryTypeBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>> _mockHandler;
private readonly GetLibraryTypeBookReadersEndpoint _sut;
private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
private readonly LibraryBookReaderResponseFixture _libraryBookReaderResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeBookReadersEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryTypeBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>>>();
_sut = Factory.Create<GetLibraryTypeBookReadersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithBookReaders()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryBookReaderResponse> expectedResponse = _libraryBookReaderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeBookReadersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<IReadOnlyList<LibraryBookReaderResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<LibraryBookReaderResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized");
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeBookReadersQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title);
Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeBookReadersQueryToSender()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryBookReaderResponse> response = _libraryBookReaderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeBookReadersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryTypeBookReadersQuery>(query => query.LibraryType == request.LibraryType),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeBookReadersQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<LibraryBookReaderResponse>>([]);
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,128 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetLibraryTypeMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Fixtures.Core.Responses.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests
{
private readonly IQueryHandler<GetLibraryTypeMetadataProvidersQuery, Result<IReadOnlyList<LibraryMetadataProviderResponse>>> _mockHandler;
private readonly GetLibraryTypeMetadataProvidersEndpoint _sut;
private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeMetadataProvidersEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryTypeMetadataProvidersQuery, Result<IReadOnlyList<LibraryMetadataProviderResponse>>>>();
_sut = Factory.Create<GetLibraryTypeMetadataProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMetadataProviders()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryMetadataProviderResponse> expectedResponse = _libraryMetadataProviderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<IReadOnlyList<LibraryMetadataProviderResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<LibraryMetadataProviderResponse>>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized");
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title);
Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryTypeMetadataProvidersQueryToSender()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryMetadataProviderResponse> response = _libraryMetadataProviderResponseFixture.CreateMany(2);
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(response));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryTypeMetadataProvidersQuery>(query => query.LibraryType == request.LibraryType),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryTypeMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(info => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From<IReadOnlyList<LibraryMetadataProviderResponse>>([]);
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -1,129 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests
{
private readonly ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>> _mockHandler;
private readonly ReorderLibraryArtworkProvidersEndpoint _sut;
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
public ReorderLibraryArtworkProvidersEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<ReorderLibraryArtworkProvidersCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<ReorderLibraryArtworkProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<ReorderLibraryArtworkProvidersCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginIds.SequenceEqual(request.PluginIds)),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryArtworkProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -1,129 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="ReorderLibraryMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryMetadataProvidersEndpointTests
{
private readonly ICommandHandler<ReorderLibraryMetadataProvidersCommand, Result<Success>> _mockHandler;
private readonly ReorderLibraryMetadataProvidersEndpoint _sut;
private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersEndpointTests"/> class.
/// </summary>
public ReorderLibraryMetadataProvidersEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<ReorderLibraryMetadataProvidersCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<ReorderLibraryMetadataProvidersEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryMetadataProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryMetadataProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryMetadataProvidersCommandToSender()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryMetadataProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<ReorderLibraryMetadataProvidersCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginIds.SequenceEqual(request.PluginIds)),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<ReorderLibraryMetadataProvidersCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -1,129 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests
{
private readonly ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>> _mockHandler;
private readonly SetLibraryArtworkProviderEnabledEndpoint _sut;
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
public SetLibraryArtworkProviderEnabledEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<SetLibraryArtworkProviderEnabledCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<SetLibraryArtworkProviderEnabledEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<SetLibraryArtworkProviderEnabledCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginId == request.PluginId &&
command.IsEnabled == request.IsEnabled),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<SetLibraryArtworkProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -1,124 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryBookReaderEnabledEndpointTests
{
private readonly ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>> _mockHandler;
private readonly SetLibraryBookReaderEnabledEndpoint _sut;
private readonly SetLibraryBookReaderEnabledRequestFixture _setLibraryBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledEndpointTests"/> class.
/// </summary>
public SetLibraryBookReaderEnabledEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<SetLibraryBookReaderEnabledEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryBookReaderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Failure("Authorization.NotAuthorized", "NotAuthorized");
_mockHandler.HandleAsync(Arg.Any<SetLibraryBookReaderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
Assert.Equal("application/problem+json", problemResult.ContentType);
Assert.Equal("Authorization.NotAuthorized", problemResult.ProblemDetails.Title);
Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryBookReaderEnabledCommandToSender()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryBookReaderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<SetLibraryBookReaderEnabledCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginId == request.PluginId &&
command.IsEnabled == request.IsEnabled),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
SetLibraryBookReaderEnabledRequest request = _setLibraryBookReaderEnabledRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<SetLibraryBookReaderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -1,129 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetLibraryMetadataProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryMetadataProviderEnabledEndpointTests
{
private readonly ICommandHandler<SetLibraryMetadataProviderEnabledCommand, Result<Success>> _mockHandler;
private readonly SetLibraryMetadataProviderEnabledEndpoint _sut;
private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledEndpointTests"/> class.
/// </summary>
public SetLibraryMetadataProviderEnabledEndpointTests()
{
_mockHandler = Substitute.For<ICommandHandler<SetLibraryMetadataProviderEnabledCommand, Result<Success>>>();
_sut = FastEndpoints.Factory.Create<SetLibraryMetadataProviderEnabledEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryMetadataProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<Success> okResult = Assert.IsType<Ok<Success>>(result);
Assert.Equal(Result.Success, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata provider configuration was not found.");
_mockHandler.HandleAsync(Arg.Any<SetLibraryMetadataProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title);
Assert.Equal("The metadata provider configuration was not found.", problemDetails.ProblemDetails.Detail);
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type);
Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryMetadataProviderEnabledCommandToSender()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<SetLibraryMetadataProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<SetLibraryMetadataProviderEnabledCommand>(command =>
command.LibraryId == request.LibraryId &&
command.PluginId == request.PluginId &&
command.IsEnabled == request.IsEnabled),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<SetLibraryMetadataProviderEnabledCommand>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(Result.Success);
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Microsoft.AspNetCore.Authorization;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using IAuthorizationService = Lumina.Presentation.Web.Common.Authorization.IAuthorizationService;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="PermissionAuthorizationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PermissionAuthorizationHandlerTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly PermissionAuthorizationHandler _sut;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAuthorizationHandlerTests"/> class.
/// </summary>
public PermissionAuthorizationHandlerTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_sut = new PermissionAuthorizationHandler(_mockAuthorizationService);
}
[Fact]
public async Task HandleAsync_WhenTheUserHoldsTheRequiredPermission_ShouldSucceed()
{
// Arrange
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenAnAdministratorLacksTheRequiredPermission_ShouldSucceed()
{
// Arrange
// The API lets administrators do what the permission allows even without holding it, so the Web must not deny them.
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.True(context.HasSucceeded);
}
[Fact]
public async Task HandleAsync_WhenAUserIsNeitherAnAdministratorNorHoldsTheRequiredPermission_ShouldNotSucceed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(Arg.Any<AuthorizationPermission>(), Arg.Any<CancellationToken>()).Returns(false);
AuthorizationHandlerContext context = CreateContext();
// Act
await _sut.HandleAsync(context);
// Assert
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Creates an authorization context that evaluates a requirement for the permission to manage media libraries.
/// </summary>
/// <returns>The created authorization context.</returns>
private static AuthorizationHandlerContext CreateContext()
{
return new AuthorizationHandlerContext([new PermissionRequirement(AuthorizationPermission.CanCreateLibraries)], new ClaimsPrincipal(), resource: null);
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeArtworkProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeArtworkProvidersEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetLibraryTypeArtworkProvidersEndpoint _sut;
private readonly GetLibraryTypeArtworkProvidersRequestFixture _getLibraryTypeArtworkProvidersRequestFixture = new();
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeArtworkProvidersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeArtworkProvidersEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetLibraryTypeArtworkProvidersEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
LibraryArtworkProviderDto[] providers = [.. _libraryArtworkProviderDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(providers);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
Assert.Equal(providers.Length, data.GetArrayLength());
Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString());
Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "Music");
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", "Music")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create(libraryType: "../plugins");
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_ARTWORK_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
{
// Arrange
GetLibraryTypeArtworkProvidersRequest request = _getLibraryTypeArtworkProvidersRequestFixture.Create();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockApiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryArtworkProviderDto[]>(
Arg.Any<string>(),
Arg.Is(cancellationToken));
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeBookReaders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeBookReadersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeBookReadersEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetLibraryTypeBookReadersEndpoint _sut;
private readonly GetLibraryTypeBookReadersRequestFixture _getLibraryTypeBookReadersRequestFixture = new();
private readonly LibraryBookReaderDtoFixture _libraryBookReaderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeBookReadersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeBookReadersEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetLibraryTypeBookReadersEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheReaders()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
LibraryBookReaderDto[] readers = [.. _libraryBookReaderDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(readers);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
Assert.Equal(readers.Length, data.GetArrayLength());
Assert.Equal(readers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
Assert.Equal(readers[0].Name, data[0].GetProperty("name").GetString());
Assert.Equal(readers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheReadersFromApiWithSubstitutedLibraryType()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "Music");
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", "Music")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create(libraryType: "../plugins");
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_BOOK_READERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
{
// Arrange
GetLibraryTypeBookReadersRequest request = _getLibraryTypeBookReadersRequestFixture.Create();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockApiHttpClient.GetAsync<LibraryBookReaderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryBookReaderDto[]>(
Arg.Any<string>(),
Arg.Is(cancellationToken));
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryTypeMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryTypeMetadataProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryTypeMetadataProvidersEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetLibraryTypeMetadataProvidersEndpoint _sut;
private readonly GetLibraryTypeMetadataProvidersRequestFixture _getLibraryTypeMetadataProvidersRequestFixture = new();
private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryTypeMetadataProvidersEndpointTests"/> class.
/// </summary>
public GetLibraryTypeMetadataProvidersEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetLibraryTypeMetadataProvidersEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithTheProviders()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
LibraryMetadataProviderDto[] providers = [.. _libraryMetadataProviderDtoFixture.CreateMany(2)];
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(providers);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
Assert.Equal(providers.Length, data.GetArrayLength());
Assert.Equal(providers[0].PluginId, data[0].GetProperty("pluginId").GetGuid());
Assert.Equal(providers[0].Name, data[0].GetProperty("name").GetString());
Assert.Equal(providers[0].IsEnabled, data[0].GetProperty("isEnabled").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestTheProvidersFromApiWithSubstitutedLibraryType()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "Music");
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", "Music")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryTypeContainsPathCharacters_ShouldEscapeItInTheApiRoute()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create(libraryType: "../plugins");
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_TYPE_METADATA_PROVIDERS.Replace("{libraryType}", Uri.EscapeDataString("../plugins"))),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
{
// Arrange
GetLibraryTypeMetadataProvidersRequest request = _getLibraryTypeMetadataProvidersRequestFixture.Create();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockApiHttpClient.GetAsync<LibraryMetadataProviderDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns([]);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryMetadataProviderDto[]>(
Arg.Any<string>(),
Arg.Is(cancellationToken));
}
}
@@ -0,0 +1,115 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.Index;
/// <summary>
/// Contains unit tests for the <see cref="LibrariesIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibrariesIndexViewEndpointTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly LibrariesIndexViewEndpoint _sut;
/// <summary>
/// Initializes a new instance of the <see cref="LibrariesIndexViewEndpointTests"/> class.
/// </summary>
public LibrariesIndexViewEndpointTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_sut = Factory.Create<LibrariesIndexViewEndpoint>(_mockAuthorizationService);
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
_sut.HttpContext.Request.Path = "/en-us/libraries/manage";
}
[Fact]
public async Task ExecuteAsync_WhenTheUserHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(true);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
Assert.True(model.CanManageLibraries);
await _mockAuthorizationService.Received(1).IsInRoleAsync("Admin", Arg.Any<CancellationToken>());
await _mockAuthorizationService.Received(1).HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheUserIsAnAdministratorWithoutTheManagePermission_ShouldRenderTheIndexViewWithManagementAllowed()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(false);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
Assert.True(model.CanManageLibraries);
await _mockAuthorizationService.DidNotReceive().HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheUserIsNeitherAnAdministratorNorHoldsTheManagePermission_ShouldRenderTheIndexViewWithManagementDenied()
{
// Arrange
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
_mockAuthorizationService.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, Arg.Any<CancellationToken>()).Returns(false);
// Act
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
// Assert
Assert.Equal("/Core/Views/Library/Management/Index.cshtml", GetRenderedViewName(result));
LibrariesIndexPageDto model = Assert.IsType<LibrariesIndexPageDto>(GetRenderedModel(result));
Assert.False(model.CanManageLibraries);
}
/// <summary>
/// Reads the private view name of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The name or path of the rendered view.</returns>
private static string GetRenderedViewName(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(viewNameField);
return (string)viewNameField.GetValue(viewResult)!;
}
/// <summary>
/// Reads the private model of the rendered <see cref="RazorViewResult"/>, which the result does not expose publicly.
/// </summary>
/// <param name="result">The result returned by the endpoint under test.</param>
/// <returns>The model passed to the rendered view.</returns>
private static object? GetRenderedModel(IResult result)
{
RazorViewResult viewResult = Assert.IsType<RazorViewResult>(result);
FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(modelField);
return modelField.GetValue(viewResult);
}
}
@@ -26,6 +26,7 @@ public class SaveLibraryEndpointTests
private readonly IApiHttpClient _mockApiHttpClient;
private readonly SaveLibraryEndpoint _sut;
private readonly LibraryDtoFixture _libraryDtoFixture = new();
private readonly LibraryProviderSelectionDtoFixture _libraryProviderSelectionDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SaveLibraryEndpointTests"/> class.
@@ -76,4 +77,29 @@ public class SaveLibraryEndpointTests
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenProviderChoicesAreMade_ShouldForwardThemToTheApi()
{
// Arrange
LibraryDto request = _libraryDtoFixture.Create();
request.Id = null;
request.MetadataProviders = _libraryProviderSelectionDtoFixture.CreateMany(2);
request.ArtworkProviders = [];
request.BookReaders = null;
_mockApiHttpClient.PostAsync<LibraryDto, LibraryDto>(Arg.Any<string>(), Arg.Any<LibraryDto>(), Arg.Any<CancellationToken>())
.Returns(_libraryDtoFixture.Create());
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PostAsync<LibraryDto, LibraryDto>(
ApiRoutes.Libraries.ADD_LIBRARY,
Arg.Is<LibraryDto>(library =>
library.MetadataProviders == request.MetadataProviders &&
library.ArtworkProviders == request.ArtworkProviders &&
library.BookReaders == null),
Arg.Any<CancellationToken>());
}
}
@@ -1,80 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetBookReaderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using EmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.SetBookReaderEnabled;
/// <summary>
/// Contains unit tests for the <see cref="SetBookReaderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetBookReaderEnabledEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly SetBookReaderEnabledEndpoint _sut;
private readonly SetBookReaderEnabledRequestFixture _setBookReaderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetBookReaderEnabledEndpointTests"/> class.
/// </summary>
public SetBookReaderEnabledEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<SetBookReaderEnabledEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJson()
{
// Arrange
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
_mockApiHttpClient.PutAsync<EmptyRequest, SetBookReaderEnabledRequest>(Arg.Any<string>(), Arg.Any<SetBookReaderEnabledRequest>(), Arg.Any<CancellationToken>())
.Returns(new EmptyRequest());
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendBookReaderEnabledChangeToApi()
{
// Arrange
SetBookReaderEnabledRequest request = _setBookReaderEnabledRequestFixture.Create();
_mockApiHttpClient.PutAsync<EmptyRequest, SetBookReaderEnabledRequest>(Arg.Any<string>(), Arg.Any<SetBookReaderEnabledRequest>(), Arg.Any<CancellationToken>())
.Returns(new EmptyRequest());
string expectedEndpoint = ApiRoutes.Libraries.SET_LIBRARY_BOOK_READER_ENABLED
.Replace("{libraryId}", request.LibraryId.ToString())
.Replace("{pluginId}", request.PluginId.ToString());
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<EmptyRequest, SetBookReaderEnabledRequest>(
expectedEndpoint,
Arg.Is<SetBookReaderEnabledRequest>(payload =>
payload.LibraryId == request.LibraryId &&
payload.PluginId == request.PluginId &&
payload.IsEnabled == request.IsEnabled),
Arg.Any<CancellationToken>());
}
}