mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 14:01:11 +00:00
Adds artwork provider system and Calibre plugin
This commit is contained in:
1 parent
c82fadc7a2
commit
6693ff3f60
124 files changed
+9715
-74
No files matched your search
+183
@@ -0,0 +1,183 @@
|
||||
#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 _configurationEntityFixture = 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>();
|
||||
_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 = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
|
||||
LibraryArtworkProviderConfigurationEntity secondProvider = _configurationEntityFixture.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 = _configurationEntityFixture.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>());
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#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();
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
#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>();
|
||||
_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>());
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
#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();
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
#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.Queries.GetLibraryArtworkProviders;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
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.Queries.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IValidator<GetLibraryArtworkProvidersQuery> _mockValidator;
|
||||
private readonly GetLibraryArtworkProvidersQueryHandler _sut;
|
||||
private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new();
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new();
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
private readonly Guid _userId;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryArtworkProvidersQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockValidator = Substitute.For<IValidator<GetLibraryArtworkProvidersQuery>>();
|
||||
_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<GetLibraryArtworkProvidersQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetLibraryArtworkProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetLibraryArtworkProvidersQuery>()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError);
|
||||
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnProvidersOrderedByRankWithPluginNames()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
Guid firstPluginId = Guid.NewGuid();
|
||||
Guid secondPluginId = Guid.NewGuid();
|
||||
List<LibraryArtworkProviderConfigurationEntity> configurations =
|
||||
[
|
||||
_configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2),
|
||||
_configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1)
|
||||
];
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(configurations));
|
||||
List<PluginEntity> plugins =
|
||||
[
|
||||
_pluginEntityFixture.Create(firstPluginId),
|
||||
_pluginEntityFixture.Create(secondPluginId)
|
||||
];
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>()).Returns(plugins);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal(firstPluginId, result.Value[0].PluginId);
|
||||
Assert.Equal(plugins[0].Name, result.Value[0].Name);
|
||||
Assert.Equal(configurations[1].Rank, result.Value[0].Rank);
|
||||
Assert.Equal(secondPluginId, result.Value[1].PluginId);
|
||||
Assert.Equal(plugins[1].Name, result.Value[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
Guid unknownPluginId = Guid.NewGuid();
|
||||
List<LibraryArtworkProviderConfigurationEntity> configurations =
|
||||
[
|
||||
_configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1)
|
||||
];
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(configurations));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<PluginEntity>>([_pluginEntityFixture.Create()]));
|
||||
|
||||
// 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_WhenNoConfigurationsExist_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IEnumerable<PluginEntity>>([]));
|
||||
|
||||
// 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_WhenGetConfigurationsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
Error error = Error.Failure(description: "Failed to get configurations");
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
|
||||
_mockPluginRepository.GetAllAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Error.Failure(description: "Failed to get plugins"));
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<LibraryArtworkProviderResponse>> result = await _sut.HandleAsync(query, 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 == query.LibraryId), Arg.Any<CancellationToken>());
|
||||
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.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);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
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.Queries.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersQueryValidatorTests
|
||||
{
|
||||
private readonly GetLibraryArtworkProvidersQueryValidator _validator = new();
|
||||
private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
query = query with { LibraryId = Guid.Empty };
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using EntityFrameworkCore.Testing.NSubstitute;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.DataAccess.Core.Repositories.Plugins;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ArtworkProviderConfigurationRepository"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ArtworkProviderConfigurationRepositoryTests
|
||||
{
|
||||
private readonly LuminaDbContext _mockContext;
|
||||
private readonly ArtworkProviderConfigurationRepository _sut;
|
||||
private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ArtworkProviderConfigurationRepositoryTests"/> class.
|
||||
/// </summary>
|
||||
public ArtworkProviderConfigurationRepositoryTests()
|
||||
{
|
||||
_mockContext = Create.MockedDbContextFor<LuminaDbContext>();
|
||||
_sut = new ArtworkProviderConfigurationRepository(_mockContext);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1);
|
||||
LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value);
|
||||
Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryIdAsync_WhenLibraryHasNoConfigurations_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<System.Collections.Generic.IReadOnlyList<LibraryArtworkProviderConfigurationEntity>> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Act
|
||||
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(configuration.Id, result.Value!.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
|
||||
// Act
|
||||
Result<LibraryArtworkProviderConfigurationEntity?> result = await _sut.GetByLibraryAndPluginIdAsync(libraryId, pluginId, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Null(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(configuration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(_mockContext.LibraryArtworkProviderConfigurations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt()
|
||||
{
|
||||
// Arrange
|
||||
LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1);
|
||||
_mockContext.LibraryArtworkProviderConfigurations.Add(configuration);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
LibraryArtworkProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5);
|
||||
updatedConfiguration.IsEnabled = true;
|
||||
|
||||
// Act
|
||||
Result<Updated> result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None);
|
||||
await _mockContext.SaveChangesAsync();
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
LibraryArtworkProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryArtworkProviderConfigurations.Single();
|
||||
Assert.Equal(5, retrievedConfiguration.Rank);
|
||||
Assert.True(retrievedConfiguration.IsEnabled);
|
||||
Assert.Equal(configuration.Id, retrievedConfiguration.Id);
|
||||
}
|
||||
}
|
||||
+541
@@ -0,0 +1,541 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Infrastructure.Fixtures.Common.Setup;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BookArtworkService"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BookArtworkServiceTests
|
||||
{
|
||||
private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
private readonly IEnvironmentContext _mockEnvironmentContext;
|
||||
private readonly IFileTypeService _mockFileTypeService;
|
||||
private readonly IFileProviderService _mockFileProviderService;
|
||||
private readonly IDirectoryProviderService _mockDirectoryProviderService;
|
||||
private readonly IPathService _mockPathService;
|
||||
private readonly IHttpClientFactory _mockHttpClientFactory;
|
||||
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
|
||||
private readonly BookArtworkService _sut;
|
||||
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
|
||||
private readonly PathSegmentFixture _pathSegmentFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
|
||||
private readonly StubHttpMessageHandler _stubHttpMessageHandler = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
|
||||
/// </summary>
|
||||
public BookArtworkServiceTests()
|
||||
{
|
||||
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
|
||||
_mockFileTypeService = Substitute.For<IFileTypeService>();
|
||||
_mockFileProviderService = Substitute.For<IFileProviderService>();
|
||||
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
|
||||
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
|
||||
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
|
||||
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
|
||||
|
||||
_mockPathService = Substitute.For<IPathService>();
|
||||
_mockPathService.PathSeparator.Returns('\\');
|
||||
|
||||
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
|
||||
_mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler));
|
||||
|
||||
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
|
||||
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
|
||||
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
|
||||
|
||||
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(copiedFileId));
|
||||
|
||||
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg");
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath);
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
|
||||
_mockFileProviderService.Received(1).CopyFile(
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
true);
|
||||
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockPathService.Received(1).SanitizeSegment("Unknown");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath()
|
||||
{
|
||||
// Arrange
|
||||
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(targetDirectory);
|
||||
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}");
|
||||
if (!TryCreateJunction(linkPath, targetDirectory))
|
||||
{
|
||||
Directory.Delete(targetDirectory, true);
|
||||
return; // the environment does not support creating reparse points
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
|
||||
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
|
||||
if (OperatingSystem.IsWindows())
|
||||
Directory.Delete(linkPath, true);
|
||||
else
|
||||
File.Delete(linkPath);
|
||||
Directory.Delete(targetDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1);
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
|
||||
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage()
|
||||
{
|
||||
// Arrange
|
||||
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.None));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError);
|
||||
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork()
|
||||
{
|
||||
// Arrange
|
||||
byte[] imageBytes = new byte[1024];
|
||||
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes);
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).CopyFile(
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path.StartsWith(Path.GetTempPath())),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound()
|
||||
{
|
||||
// Arrange
|
||||
_stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge()
|
||||
{
|
||||
// Arrange
|
||||
_stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]);
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string sourcePath = CreateTempImageFile(smallImageBytes: 1024);
|
||||
try
|
||||
{
|
||||
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
|
||||
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(ImageType.JPEG));
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
|
||||
FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
|
||||
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
|
||||
.Returns(Result.From(renamedFileId));
|
||||
|
||||
// Act
|
||||
Result<string> result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.True(File.Exists(sourcePath));
|
||||
_mockFileProviderService.Received(1).CopyFile(
|
||||
Arg.Is<FileSystemPathId>(pathId => pathId.Path == sourcePath),
|
||||
Arg.Any<FileSystemPathId>(),
|
||||
true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(sourcePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation()
|
||||
{
|
||||
// Arrange
|
||||
CancellationTokenSource cancellationTokenSource = new();
|
||||
cancellationTokenSource.Cancel();
|
||||
|
||||
// Act
|
||||
async Task Act()
|
||||
{
|
||||
await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
string libraryName = "Test Library";
|
||||
string authorName = "Test Author";
|
||||
string bookTitle = "Test Book";
|
||||
|
||||
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
MockArtworkDirectoryStubs(artworkDirectoryPath);
|
||||
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg"));
|
||||
FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json"));
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
|
||||
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
|
||||
_mockFileProviderService.DidNotReceive().DeleteFile(otherFileId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
|
||||
{
|
||||
// Arrange
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(Errors.FileSystemManagement.InvalidPath);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title");
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the path and file system services so that the artwork is stored into the given directory.
|
||||
/// </summary>
|
||||
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
|
||||
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
|
||||
{
|
||||
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
|
||||
string booksPath = Path.Combine(mediaRoot, "books");
|
||||
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
|
||||
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
|
||||
|
||||
_mockPathService.SanitizeSegment(Arg.Any<string>())
|
||||
.Returns(callInfo =>
|
||||
{
|
||||
string name = callInfo.Arg<string>();
|
||||
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
|
||||
});
|
||||
|
||||
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
|
||||
|
||||
// every directory except the artwork directory itself already exists, so that only the final directory is created
|
||||
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
|
||||
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
|
||||
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
|
||||
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
|
||||
|
||||
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
|
||||
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the file system path of the directory that the artwork of the book is stored into.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryName">The name of the media library the book belongs to.</param>
|
||||
/// <param name="authorName">The name of the author of the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <returns>The expected file system path of the book artwork directory.</returns>
|
||||
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
|
||||
{
|
||||
return Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"media",
|
||||
"books",
|
||||
$"{libraryName}-{libraryId}",
|
||||
authorName,
|
||||
$"{bookTitle}-{bookId}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temporary image file with the given size and returns its path.
|
||||
/// </summary>
|
||||
/// <param name="smallImageBytes">The size of the temporary image file, in bytes.</param>
|
||||
/// <returns>The file system path of the created temporary image file.</returns>
|
||||
private static string CreateTempImageFile(int smallImageBytes)
|
||||
{
|
||||
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg");
|
||||
File.WriteAllBytes(sourcePath, new byte[smallImageBytes]);
|
||||
return sourcePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
|
||||
/// </summary>
|
||||
/// <param name="linkPath">The file system path of the link to create.</param>
|
||||
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
|
||||
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
|
||||
private static bool TryCreateJunction(string linkPath, string targetDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
|
||||
? new()
|
||||
{
|
||||
FileName = "cmd.exe",
|
||||
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false
|
||||
}
|
||||
: new()
|
||||
{
|
||||
FileName = "ln",
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
startInfo.ArgumentList.Add("-s");
|
||||
startInfo.ArgumentList.Add(targetDirectory);
|
||||
startInfo.ArgumentList.Add(linkPath);
|
||||
}
|
||||
|
||||
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
|
||||
process.WaitForExit(5000);
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Calibre.Core;
|
||||
using Lumina.Plugins.Calibre.Fixtures.Core.Metadata;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CalibreArtworkProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CalibreArtworkProviderTests
|
||||
{
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
private readonly TestMetadataLookupFixture _testMetadataLookupFixture = new();
|
||||
private readonly CalibreArtworkProvider _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Calibre", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal(LibraryType.Book, result[0]);
|
||||
Assert.Equal(LibraryType.EBook, result[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
WriteOpf(bookDirectory, coverHref: "cover.jpg");
|
||||
File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath);
|
||||
Assert.Null(result.RemoteUrl);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../cover.jpg")] // parent directory escape
|
||||
[InlineData("sub/cover.jpg")] // path with a separator
|
||||
[InlineData("sub\\cover.jpg")] // path with a backslash separator
|
||||
public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref)
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
WriteOpf(bookDirectory, coverHref);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
WriteOpf(bookDirectory, coverHref: "cover.jpg");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata></package>""");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
MetadataLookupDto lookup = _testMetadataLookupFixture.Create();
|
||||
IArtworkProvider baseProvider = _sut;
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ");
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an OPF file that references the given cover into the book directory.
|
||||
/// </summary>
|
||||
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
|
||||
/// <param name="coverHref">The href of the cover the OPF file references.</param>
|
||||
private static void WriteOpf(string bookDirectory, string coverHref)
|
||||
{
|
||||
string opf = $$"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata><guide><reference type="cover" href="{{coverHref}}"/></guide></package>""";
|
||||
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique temporary directory for the book.
|
||||
/// </summary>
|
||||
/// <returns>The file system path of the created temporary directory.</returns>
|
||||
private static string CreateTempDirectory()
|
||||
{
|
||||
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
return directoryPath;
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Calibre.Core;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CalibreBookMetadataProvider"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CalibreBookMetadataProviderTests
|
||||
{
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
private readonly CalibreBookMetadataProvider _sut = new();
|
||||
|
||||
private const string OPF_DOCUMENT = """<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator></metadata></package>""";
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnTheProviderDisplayName()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Calibre", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<LibraryType> result = _sut.SupportedLibraryTypes;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal(LibraryType.Book, result[0]);
|
||||
Assert.Equal(LibraryType.EBook, result[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiresWebAccess_WhenCalled_ShouldReturnFalse()
|
||||
{
|
||||
// Act
|
||||
bool result = _sut.RequiresWebAccess;
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Test Book Title", result!.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ");
|
||||
|
||||
// Act
|
||||
BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT);
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
BookMetadataDto metadata = Assert.IsType<BookMetadataDto>(Assert.Single(result));
|
||||
Assert.Equal("Test Book Title", metadata.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
string bookDirectory = CreateTempDirectory();
|
||||
try
|
||||
{
|
||||
string bookPath = Path.Combine(bookDirectory, "book.epub");
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath);
|
||||
|
||||
// Act
|
||||
IReadOnlyList<BookMetadataDto> result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(bookDirectory, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a unique temporary directory for the book.
|
||||
/// </summary>
|
||||
/// <returns>The file system path of the created temporary directory.</returns>
|
||||
private static string CreateTempDirectory()
|
||||
{
|
||||
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directoryPath);
|
||||
return directoryPath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Core;
|
||||
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.UnitTests.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CalibrePlugin"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CalibrePluginTests
|
||||
{
|
||||
private readonly CalibrePlugin _sut = new();
|
||||
|
||||
[Fact]
|
||||
public void Id_WhenCalled_ShouldReturnStablePluginIdentifier()
|
||||
{
|
||||
// Act
|
||||
Guid result = _sut.Id;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(CalibrePlugin.s_pluginId, result);
|
||||
Assert.Equal(new Guid("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Name_WhenCalled_ShouldReturnPluginDisplayName()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Name;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Calibre Metadata", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Author_WhenCalled_ShouldReturnPluginAuthor()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Author;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Lumina", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Version_WhenCalled_ShouldReturnPluginVersion()
|
||||
{
|
||||
// Act
|
||||
Version result = _sut.Version;
|
||||
|
||||
// Assert
|
||||
Assert.Equal(new Version(1, 0, 0), result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Description_WhenCalled_ShouldReturnPluginDescription()
|
||||
{
|
||||
// Act
|
||||
string result = _sut.Description;
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Reads book metadata and covers from the OPF files of a Calibre library.", result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema()
|
||||
{
|
||||
// Act
|
||||
IReadOnlyList<PluginSettingDescriptorDto> result = _sut.GetSettingsSchema();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataAndArtworkProviders()
|
||||
{
|
||||
// Arrange
|
||||
ServiceCollection services = new();
|
||||
|
||||
// Act
|
||||
_sut.RegisterServices(services);
|
||||
ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(serviceProvider.GetKeyedService<IMetadataProvider>(CalibrePlugin.s_pluginId));
|
||||
Assert.NotNull(serviceProvider.GetKeyedService<IArtworkProvider>(CalibrePlugin.s_pluginId));
|
||||
Assert.Null(serviceProvider.GetKeyedService<IMetadataProvider>(Guid.NewGuid()));
|
||||
Assert.Null(serviceProvider.GetKeyedService<IArtworkProvider>(Guid.NewGuid()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using Lumina.Plugins.Calibre.Core.Mapping;
|
||||
using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.UnitTests.Core.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="CalibreMapper"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CalibreMapperTests
|
||||
{
|
||||
private readonly OpfDocumentDtoFixture _opfDocumentDtoFixture = new();
|
||||
private readonly OpfCreatorDtoFixture _opfCreatorDtoFixture = new();
|
||||
private readonly OpfContributorDtoFixture _opfContributorDtoFixture = new();
|
||||
private readonly OpfIdentifierDtoFixture _opfIdentifierDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenDocumentHasAllFields_ShouldMapThemToTheBookMetadataDto()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(
|
||||
title: "Test Book Title",
|
||||
description: "<p>A test description with <b>markup</b>. </p>",
|
||||
publisher: "Test Publisher",
|
||||
publishDate: new DateTimeOffset(2015, 6, 15, 0, 0, 0, TimeSpan.Zero),
|
||||
languageCode: "en",
|
||||
series: "The Series",
|
||||
seriesIndex: 2.5,
|
||||
rating: 8,
|
||||
subjects: ["Science fiction", "Space opera"],
|
||||
creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", "oth")],
|
||||
contributors:
|
||||
[
|
||||
_opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"),
|
||||
_opfContributorDtoFixture.Create("Test Translator", "trl")
|
||||
],
|
||||
identifiers:
|
||||
[
|
||||
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
|
||||
_opfIdentifierDtoFixture.Create("goodreads", "123456"),
|
||||
_opfIdentifierDtoFixture.Create("ASIN", "B00TEST1"),
|
||||
_opfIdentifierDtoFixture.Create("lccn", "test-lccn"),
|
||||
_opfIdentifierDtoFixture.Create("oclc", "ocm12345678"),
|
||||
_opfIdentifierDtoFixture.Create("openlibrary", "OL100M"),
|
||||
_opfIdentifierDtoFixture.Create("google", "google-id")
|
||||
]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Test Book Title", result.Title);
|
||||
Assert.Equal("A test description with markup .", result.Description);
|
||||
Assert.Equal("Test Publisher", result.Publisher);
|
||||
Assert.NotNull(result.ReleaseInfo);
|
||||
Assert.Equal(new DateOnly(2015, 6, 15), result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Equal(2015, result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Equal("The Series", result.Series!.Title);
|
||||
Assert.Equal(2.5f, result.VolumeNumber);
|
||||
Assert.Equal("B00TEST1", result.ASIN);
|
||||
Assert.Equal("123456", result.GoodreadsId);
|
||||
Assert.Equal("test-lccn", result.LCCN);
|
||||
Assert.Equal("ocm12345678", result.OCLCNumber);
|
||||
Assert.Equal("OL100M", result.OpenLibraryId);
|
||||
Assert.Equal("google-id", result.GoogleBooksId);
|
||||
Assert.Null(result.Genres);
|
||||
Assert.Null(result.CoverImagePath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenDescriptionContainsHtmlEntities_ShouldDecodeAndStripThem()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: "A & B <tag>description</tag> with multiple spaces");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("A & B description with multiple spaces", result.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenDescriptionIsEmpty_ShouldReturnNullDescription()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: " ");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Description);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // a zero series index is not a meaningful volume number
|
||||
public void Map_WhenSeriesIndexIsZero_ShouldReturnNullVolumeNumber(double seriesIndex)
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(seriesIndex: seriesIndex);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.VolumeNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenSeriesIndexIsNull_ShouldReturnNullVolumeNumber()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.VolumeNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenSeriesIsNull_ShouldReturnNullSeries()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Series);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenRatingIsPresent_ShouldMapItToACalibreRatingWithMaxValueTen()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(rating: 8);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
BookRatingDto rating = Assert.Single(result.Ratings!);
|
||||
Assert.Equal(8m, rating.Value);
|
||||
Assert.Equal(10m, rating.MaxValue);
|
||||
Assert.Equal(BookRatingSource.Calibre, rating.Source);
|
||||
Assert.Null(rating.VoteCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenRatingIsMissing_ShouldReturnNullRatings()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenSubjectsArePresent_ShouldMapThemToTagsWithNullGenres()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(subjects: ["Science fiction", "Space opera"]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Genres);
|
||||
Assert.Equal(2, result.Tags!.Count);
|
||||
Assert.Equal("Science fiction", result.Tags[0].Name);
|
||||
Assert.Equal("Space opera", result.Tags[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenCreatorsAndContributorsArePresent_ShouldMapRolesAndCategories()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(
|
||||
creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", null)],
|
||||
contributors:
|
||||
[
|
||||
_opfContributorDtoFixture.Create("Test Translator", "trl"),
|
||||
_opfContributorDtoFixture.Create("Test Illustrator", "ill"),
|
||||
_opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"),
|
||||
_opfContributorDtoFixture.Create("Misc Contributor", null)
|
||||
]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(6, result.Contributors!.Count);
|
||||
|
||||
MediaContributorDto author = result.Contributors[0];
|
||||
Assert.Equal("Test Author", author.Name!.DisplayName);
|
||||
Assert.Equal("Author", author.Role!.Name);
|
||||
Assert.Equal("Writing", author.Role.Category);
|
||||
|
||||
MediaContributorDto coAuthor = result.Contributors[1];
|
||||
Assert.Equal("Co Author", coAuthor.Name!.DisplayName);
|
||||
Assert.Equal("Author", coAuthor.Role!.Name);
|
||||
Assert.Equal("Writing", coAuthor.Role.Category);
|
||||
|
||||
MediaContributorDto translator = result.Contributors[2];
|
||||
Assert.Equal("Test Translator", translator.Name!.DisplayName);
|
||||
Assert.Equal("trl", translator.Role!.Name);
|
||||
Assert.Equal("Translation", translator.Role.Category);
|
||||
|
||||
MediaContributorDto illustrator = result.Contributors[3];
|
||||
Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName);
|
||||
Assert.Equal("ill", illustrator.Role!.Name);
|
||||
Assert.Equal("Art", illustrator.Role.Category);
|
||||
|
||||
MediaContributorDto production = result.Contributors[4];
|
||||
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName);
|
||||
Assert.Equal("bkp", production.Role!.Name);
|
||||
Assert.Equal("Production", production.Role.Category);
|
||||
|
||||
MediaContributorDto misc = result.Contributors[5];
|
||||
Assert.Equal("Misc Contributor", misc.Name!.DisplayName);
|
||||
Assert.Equal("Contributor", misc.Role!.Name);
|
||||
Assert.Equal("Other", misc.Role.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenCreatorsAreDuplicatedWithTheSameRole_ShouldDeDuplicateThem()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Test Author", "aut")]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
MediaContributorDto author = Assert.Single(result.Contributors!);
|
||||
Assert.Equal("Test Author", author.Name!.DisplayName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenIsbnIdentifiersArePresent_ShouldNormalizeAndMapThem()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers:
|
||||
[
|
||||
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
|
||||
_opfIdentifierDtoFixture.Create("ISBN", "0306406152"),
|
||||
_opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"),
|
||||
_opfIdentifierDtoFixture.Create("ISBN", "not-an-isbn")
|
||||
]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Isbns!.Count);
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13);
|
||||
Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenNoIdentifiersArePresent_ShouldReturnEmptyIsbnList()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Isbns!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenAmazonIdentifiersArePresent_ShouldMapAsin()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: [_opfIdentifierDtoFixture.Create("amazon", "B00TEST1")]);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("B00TEST1", result.ASIN);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenLanguageCodeIsUnknown_ShouldReturnTheRawCode()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: "zz");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("zz", result.Language!.LanguageCode);
|
||||
Assert.Equal("zz", result.Language.LanguageName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenLanguageCodeIsEmpty_ShouldReturnNullLanguage()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: " ");
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Language);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenDocumentHasNoMetadata_ShouldReturnEmptyDto()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create();
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Null(result.Description);
|
||||
Assert.NotNull(result.ReleaseInfo);
|
||||
Assert.Null(result.Publisher);
|
||||
Assert.Null(result.Series);
|
||||
Assert.Null(result.VolumeNumber);
|
||||
Assert.Null(result.Ratings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_WhenPublishDateIsMissing_ShouldReturnEmptyReleaseInfo()
|
||||
{
|
||||
// Arrange
|
||||
OpfDocumentDto document = _opfDocumentDtoFixture.Create(publishDate: null);
|
||||
|
||||
// Act
|
||||
BookMetadataDto result = CalibreMapper.Map(document);
|
||||
|
||||
// Assert
|
||||
// a book without a publication date must still be enrichable, so the release info is present with empty fields
|
||||
Assert.NotNull(result.ReleaseInfo);
|
||||
Assert.Null(result.ReleaseInfo!.OriginalReleaseDate);
|
||||
Assert.Null(result.ReleaseInfo.OriginalReleaseYear);
|
||||
Assert.Null(result.ReleaseInfo.ReReleaseDate);
|
||||
Assert.Null(result.ReleaseInfo.ReReleaseYear);
|
||||
Assert.Null(result.ReleaseInfo.ReleaseCountry);
|
||||
Assert.Null(result.ReleaseInfo.ReleaseVersion);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Plugins.Calibre.Common.Models.DTO.Opf;
|
||||
using Lumina.Plugins.Calibre.Core.Opf;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="OpfReader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class OpfReaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileContainsAllSupportedFields_ShouldParseThemAll()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="uuid_id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"><dc:title>Test Book Title</dc:title><dc:creator opf:role="aut">Test Author</dc:creator><dc:creator opf:role="oth">Second Creator</dc:creator><dc:contributor opf:role="bkp">calibre (3.48.0) [https://calibre-ebook.com]</dc:contributor><dc:contributor opf:role="trl">Test Translator</dc:contributor><dc:description><p>A test description with <b>markup</b>.</p></dc:description><dc:publisher>Test Publisher</dc:publisher><dc:date>2015-06-15</dc:date><dc:language>en</dc:language><dc:identifier opf:scheme="ISBN">978-0-306-40615-7</dc:identifier><dc:identifier opf:scheme="goodreads">123456</dc:identifier><dc:identifier opf:scheme="ASIN">B00TEST1</dc:identifier><dc:identifier opf:scheme="LCCN">test-lccn</dc:identifier><dc:identifier opf:scheme="oclc">ocm12345678</dc:identifier><dc:identifier opf:scheme="openlibrary">OL100M</dc:identifier><dc:identifier opf:scheme="google">google-id</dc:identifier><dc:subject>Science fiction</dc:subject><dc:subject>Space opera</dc:subject><meta name="calibre:series" content="The Series"/><meta name="calibre:series_index" content="2.5"/><meta name="calibre:rating" content="8"/></metadata><guide><reference type="cover" href="cover.jpg"/><reference type="toc" href="toc.xhtml"/></guide></package>""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("Test Book Title", result.Title);
|
||||
Assert.Equal("<p>A test description with <b>markup</b>.</p>", result.Description);
|
||||
Assert.Equal("Test Publisher", result.Publisher);
|
||||
Assert.Equal(2015, result.PublishDate!.Value.Year);
|
||||
Assert.Equal(6, result.PublishDate.Value.Month);
|
||||
Assert.Equal(15, result.PublishDate.Value.Day);
|
||||
Assert.Equal("en", result.LanguageCode);
|
||||
Assert.Equal("The Series", result.Series);
|
||||
Assert.Equal(2.5, result.SeriesIndex);
|
||||
Assert.Equal(8, result.Rating);
|
||||
Assert.Equal("cover.jpg", result.CoverHref);
|
||||
Assert.Equal(2, result.Creators.Count);
|
||||
Assert.Equal("Test Author", result.Creators[0].Name);
|
||||
Assert.Equal("aut", result.Creators[0].Role);
|
||||
Assert.Equal(2, result.Contributors.Count);
|
||||
Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", result.Contributors[0].Name);
|
||||
Assert.Equal("bkp", result.Contributors[0].Role);
|
||||
Assert.Equal(7, result.Identifiers.Count);
|
||||
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ISBN" && identifier.Value == "978-0-306-40615-7");
|
||||
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "goodreads" && identifier.Value == "123456");
|
||||
Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ASIN" && identifier.Value == "B00TEST1");
|
||||
Assert.Equal(2, result.Subjects.Count);
|
||||
Assert.Equal("Science fiction", result.Subjects[0]);
|
||||
Assert.Equal("Space opera", result.Subjects[1]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileDoesNotExist_ShouldReturnEmptyDocument()
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.opf"));
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Empty(result.Identifiers);
|
||||
Assert.Empty(result.Creators);
|
||||
Assert.Empty(result.Subjects);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenMetadataContainsWhitespaceOnlyValues_ShouldSkipThem()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title> </dc:title><dc:creator opf:role="aut"> </dc:creator><dc:subject></dc:subject></metadata></package>""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Empty(result.Creators);
|
||||
Assert.Empty(result.Subjects);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenMetadataElementIsMissing_ShouldReturnEmptyDocument()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"></package>""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Empty(result.Identifiers);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem()
|
||||
{
|
||||
// Arrange
|
||||
// the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title
|
||||
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&xxe;</dc:title></metadata></package>""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandThem()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = CreateOpfFile("""<?xml version="1.0" encoding="utf-8"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&lol3;</dc:title></metadata></package>""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileIsOversized_ShouldReturnEmptyDocument()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = Path.Combine(Path.GetTempPath(), $"oversized-{Guid.NewGuid():N}.opf");
|
||||
string oversizedContent = $"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{new string('a', (5 * 1024 * 1024) + 100)}</dc:title></metadata></package>""";
|
||||
File.WriteAllText(opfFilePath, oversizedContent);
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Empty(result.Identifiers);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Read_WhenOpfFileIsMalformedXml_ShouldReturnEmptyDocument()
|
||||
{
|
||||
// Arrange
|
||||
string opfFilePath = CreateOpfFile("""<package xmlns="http://www.idpf.org/2007/opf"><metadata><dc:title>Unclosed""");
|
||||
|
||||
try
|
||||
{
|
||||
// Act
|
||||
OpfDocumentDto result = OpfReader.Read(opfFilePath);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.Title);
|
||||
Assert.Empty(result.Identifiers);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(opfFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a temporary OPF file with the given content and returns its path.
|
||||
/// </summary>
|
||||
/// <param name="content">The content of the OPF file to create.</param>
|
||||
/// <returns>The file system path of the created OPF file.</returns>
|
||||
private static string CreateOpfFile(string content)
|
||||
{
|
||||
string opfFilePath = Path.Combine(Path.GetTempPath(), $"opf-{Guid.NewGuid():N}.opf");
|
||||
File.WriteAllText(opfFilePath, content);
|
||||
return opfFilePath;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
|
||||
<_Parameter1>DisableTestParallelization = true</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoFixture.AutoNSubstitute" />
|
||||
<PackageReference Include="AutoFixture.Xunit2" />
|
||||
<PackageReference Include="Bogus" />
|
||||
<PackageReference Include="coverlet.collector">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="NSubstitute" />
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Plugins.Calibre.Fixtures\Lumina.Plugins.Calibre.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.Common;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.Common;
|
||||
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Plugins.Contracts.Core.Metadata;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="IArtworkProvider{TLookup}"/> interface.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class IArtworkProviderGenericTests
|
||||
{
|
||||
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
|
||||
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
|
||||
private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation()
|
||||
{
|
||||
// Arrange
|
||||
BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
ArtworkDto expectedArtwork = _artworkDtoFixture.Create();
|
||||
TestBookArtworkProvider provider = new(expectedArtwork);
|
||||
IArtworkProvider baseProvider = provider;
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedArtwork, result);
|
||||
Assert.Same(lookup, provider.ReceivedLookup);
|
||||
Assert.Equal(cancellationToken, provider.ReceivedCancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create();
|
||||
TestBookArtworkProvider provider = new(_artworkDtoFixture.Create());
|
||||
IArtworkProvider baseProvider = provider;
|
||||
|
||||
// Act
|
||||
ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
Assert.Null(provider.ReceivedLookup);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test double for the typed artwork provider interface that records the forwarded arguments.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
private sealed class TestBookArtworkProvider : IArtworkProvider<BookMetadataLookupDto>
|
||||
{
|
||||
private readonly ArtworkDto _artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the lookup that was forwarded to the typed implementation.
|
||||
/// </summary>
|
||||
public BookMetadataLookupDto? ReceivedLookup { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cancellation token that was forwarded to the typed implementation.
|
||||
/// </summary>
|
||||
public CancellationToken ReceivedCancellationToken { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="TestBookArtworkProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="artwork">The artwork returned by the typed implementation.</param>
|
||||
public TestBookArtworkProvider(ArtworkDto artwork)
|
||||
{
|
||||
_artwork = artwork;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string Name => "Test Provider";
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Book];
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool RequiresWebAccess => false;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Task<ArtworkDto?> GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken)
|
||||
{
|
||||
ReceivedLookup = lookup;
|
||||
ReceivedCancellationToken = cancellationToken;
|
||||
return Task.FromResult<ArtworkDto?>(_artwork);
|
||||
}
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders;
|
||||
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.GetLibraryArtworkProviders;
|
||||
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.GetLibraryArtworkProviders;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibraryArtworkProvidersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibraryArtworkProvidersEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>> _mockHandler;
|
||||
private readonly GetLibraryArtworkProvidersEndpoint _sut;
|
||||
private readonly GetLibraryArtworkProvidersRequestFixture _getLibraryArtworkProvidersRequestFixture = new();
|
||||
private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryArtworkProvidersEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetLibraryArtworkProvidersQuery, Result<IReadOnlyList<LibraryArtworkProviderResponse>>>>();
|
||||
_sut = Factory.Create<GetLibraryArtworkProvidersEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryArtworkProviderResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IReadOnlyList<LibraryArtworkProviderResponse> expectedResponses =
|
||||
[
|
||||
_libraryArtworkProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1),
|
||||
_libraryArtworkProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2)
|
||||
];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponses));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<LibraryArtworkProviderResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<LibraryArtworkProviderResponse>>>(result);
|
||||
Assert.Equal(expectedResponses, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.NotFound("Library.NotFound", "The requested library was not found.");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), 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("Library.NotFound", problemDetails.ProblemDetails.Title);
|
||||
Assert.Equal("The requested library 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_ShouldSendGetLibraryArtworkProvidersQueryToSender()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderResponse>>([]));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetLibraryArtworkProvidersQuery>(query => query.LibraryId == request.LibraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetLibraryArtworkProvidersQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From<IReadOnlyList<LibraryArtworkProviderResponse>>([]);
|
||||
}, 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);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#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_WhenHandlerReturnsError_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);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#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_WhenHandlerReturnsError_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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user