Adds metadata aggregation to the media library enrichment job

This commit is contained in:
BinaryAlley committed 2026-08-24 14:18:40 -07:00
1 parent c82fadc7a2
commit 66871ccf62
168 files changed
+3503 -1062

No files matched your search

@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
@@ -14,20 +15,22 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
AddLibraryRequest request = new(
"My Library",
"Book",
["C:/Books", "D:/Media/Books"],
"D:/poster.jpg",
true,
false,
true,
false,
false
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "My Library",
libraryType: "Book",
contentLocations: ["C:/Books", "D:/Media/Books"],
coverImage: "D:/poster.jpg",
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false
);
// Act
@@ -41,7 +44,7 @@ public class AddMediaLibraryRequestMappingTests
Assert.Equal(request.CoverImage, result.CoverImage);
Assert.Equal(request.IsEnabled, result.IsEnabled);
Assert.Equal(request.IsLocked, result.IsLocked);
Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb);
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
}
@@ -53,16 +56,16 @@ public class AddMediaLibraryRequestMappingTests
public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
{
// Arrange
AddLibraryRequest request = new(
"My Library",
libraryType.ToString(),
["C:/Media"],
"D:/poster.jpg",
true,
false,
true,
false,
false
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "My Library",
libraryType: libraryType.ToString(),
contentLocations: ["C:/Media"],
coverImage: "D:/poster.jpg",
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false
);
// Act
@@ -76,7 +79,7 @@ public class AddMediaLibraryRequestMappingTests
Assert.Equal(request.CoverImage, result.CoverImage);
Assert.Equal(request.IsEnabled, result.IsEnabled);
Assert.Equal(request.IsLocked, result.IsLocked);
Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb);
Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb);
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
}
@@ -92,16 +95,16 @@ public class AddMediaLibraryRequestMappingTests
"F:/Reading Material"
];
AddLibraryRequest request = new(
"My Library",
"Book",
contentLocations,
"D:/poster.jpg",
true,
false,
true,
false,
false
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "My Library",
libraryType: "Book",
contentLocations: contentLocations,
coverImage: "D:/poster.jpg",
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false
);
// Act
@@ -122,16 +125,16 @@ public class AddMediaLibraryRequestMappingTests
"D:/Books"
];
AddLibraryRequest request = new(
"My Library",
"Book",
contentLocations,
null,
true,
false,
true,
false,
false
AddLibraryRequest request = _addLibraryRequestFixture.Create(
title: "My Library",
libraryType: "Book",
contentLocations: contentLocations,
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false
);
// Act
@@ -1,9 +1,9 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
@@ -17,28 +17,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class LibraryEntityMappingTests
{
private readonly LibraryEntityFixture _libraryEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly()
{
// Arrange
LibraryEntity entity = new()
{
Id = Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = "My Library",
LibraryType = LibraryType.Book,
ContentLocations =
[
new() { Path = "C:/Books" },
new() { Path = "D:/Media/Books" }
],
CoverImage = "D:/myPoster.jpg",
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null,
LibraryScans = []
};
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books", "D:/Media/Books"],
coverImage: "D:/myPoster.jpg");
// Act
LibraryResponse result = entity.ToResponse();
@@ -63,19 +52,11 @@ public class LibraryEntityMappingTests
public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType)
{
// Arrange
LibraryEntity entity = new()
{
Id = Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = "My Library",
LibraryType = libraryType,
ContentLocations = [new() { Path = "C:/Media" }],
CoverImage = "D:/myPoster.jpg",
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
};
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: libraryType,
contentLocations: ["C:/Media"],
coverImage: "D:/myPoster.jpg");
// Act
LibraryResponse result = entity.ToResponse();
@@ -89,25 +70,11 @@ public class LibraryEntityMappingTests
public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly()
{
// Arrange
LibraryEntity entity = new()
{
Id = Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = "My Library",
LibraryType = LibraryType.Book,
ContentLocations =
[
new() { Path = "C:/Media/Books" },
new() { Path = "D:/Books" },
new() { Path = "E:/Digital Library/Books" },
new() { Path = "F:/Reading Material" }
],
CoverImage = "D:/myPoster.jpg",
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = null,
UpdatedBy = null
};
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Media/Books", "D:/Books", "E:/Digital Library/Books", "F:/Reading Material"],
coverImage: "D:/myPoster.jpg");
// Act
LibraryResponse result = entity.ToResponse();
@@ -122,19 +89,12 @@ public class LibraryEntityMappingTests
{
// Arrange
DateTime updated = DateTime.UtcNow.AddDays(-1);
LibraryEntity entity = new()
{
Id = Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = "My Library",
LibraryType = LibraryType.Book,
ContentLocations = [new() { Path = "C:/Books" }],
CoverImage = "D:/myPoster.jpg",
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = updated,
UpdatedBy = Guid.NewGuid()
};
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
coverImage: "D:/myPoster.jpg");
entity.UpdatedOnUtc = updated;
// Act
LibraryResponse result = entity.ToResponse();
@@ -149,19 +109,12 @@ public class LibraryEntityMappingTests
{
// Arrange
DateTime updated = DateTime.UtcNow.AddDays(-1);
LibraryEntity entity = new()
{
Id = Guid.NewGuid(),
UserId = Guid.NewGuid(),
Title = "My Library",
LibraryType = LibraryType.Book,
ContentLocations = [new() { Path = "C:/Books" }],
CoverImage = null,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedOnUtc = updated,
UpdatedBy = Guid.NewGuid()
};
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"]);
entity.CoverImage = null;
entity.UpdatedOnUtc = updated;
// Act
LibraryResponse result = entity.ToResponse();
@@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
@@ -34,7 +33,7 @@ public class LibraryMappingTests
coverImage: "D:/myPoster.jpg",
isEnabled: true,
isLocked: false,
downloadMetadataFromWeb: true,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
scanIds: [Guid.NewGuid()]);
@@ -54,7 +53,7 @@ public class LibraryMappingTests
Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc);
Assert.True(result.IsEnabled);
Assert.False(result.IsLocked);
Assert.True(result.DownloadMetadataFromWeb);
Assert.True(result.CanDownloadMetadataFromWeb);
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id));
}
@@ -93,7 +92,7 @@ public class LibraryMappingTests
coverImage: "D:/myPoster.jpg",
isEnabled: true,
isLocked: false,
downloadMetadataFromWeb: true,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false);
// Act
@@ -105,7 +104,7 @@ public class LibraryMappingTests
Assert.Equal(library.CoverImage, result.CoverImage);
Assert.True(result.IsEnabled);
Assert.False(result.IsLocked);
Assert.True(result.DownloadMetadataFromWeb);
Assert.True(result.CanDownloadMetadataFromWeb);
Assert.False(result.ShouldSaveMetadataInMediaDirectories);
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -13,11 +14,19 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users;
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsRequestMappingTests
{
private readonly UpdateUserSettingsRequestFixture _requestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
{
// Arrange
UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false, IsThemeCachingEnabled: true);
UpdateUserSettingsRequest request = _requestFixture.Create(
isPaginationEnabled: true,
itemsPerPage: 48,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: true,
shouldAggregateMetadataWhenMissing: false
);
// Act
UpdateUserSettingsCommand result = request.ToCommand();
@@ -26,7 +35,7 @@ public class UpdateUserSettingsRequestMappingTests
Assert.NotNull(result);
Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(request.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
}
}
@@ -33,7 +33,7 @@ public class UserSettingsEntityMappingTests
Assert.Equal(entity.UserId, result.Value.UserId.Value);
Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled);
Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage);
Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled);
}
@@ -51,7 +51,7 @@ public class UserSettingsEntityMappingTests
Assert.Equal(entity.UserId, result.UserId);
Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled);
}
}
@@ -34,7 +34,7 @@ public class UserSettingsMappingTests
Assert.Equal(userId, result.UserId);
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
}
[Fact]
@@ -52,6 +52,6 @@ public class UserSettingsMappingTests
Assert.Equal(userId, result.UserId);
Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled);
Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage);
Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker);
Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker);
}
}
@@ -2,17 +2,22 @@
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders;
@@ -25,8 +30,13 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<ReorderLibraryMetadataProvidersCommand> _mockValidator;
private readonly ReorderLibraryMetadataProvidersCommandHandler _sut;
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryMetadataProvidersCommandHandlerTests"/> class.
@@ -36,10 +46,18 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<ReorderLibraryMetadataProvidersCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>())
.Returns([]);
_sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, _mockValidator);
_sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
@@ -47,16 +65,15 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntityFixture configurationFixture = new();
LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 1);
LibraryMetadataProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2);
LibraryMetadataProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1);
_mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any<CancellationToken>())
.Returns(new List<LibraryMetadataProviderConfigurationEntity> { firstProvider, secondProvider });
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -76,7 +93,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
_mockValidator.Validate(Arg.Any<ReorderLibraryMetadataProvidersCommand>()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [Guid.NewGuid()]), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -85,4 +102,42 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -2,16 +2,22 @@
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled;
@@ -24,8 +30,17 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<SetLibraryMetadataProviderEnabledCommand> _mockValidator;
private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut;
private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new();
private readonly Guid _userId;
/// <summary>
/// Fixture for generating <see cref="LibraryMetadataProviderConfigurationEntity"/> test data.
/// </summary>
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryMetadataProviderEnabledCommandHandlerTests"/> class.
@@ -35,10 +50,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<SetLibraryMetadataProviderEnabledCommand>>();
_userId = Guid.NewGuid();
// default stubs: the current user is authenticated and the library ownership policy allows access
_mockCurrentUserService.UserId.Returns(_userId);
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(true);
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>())
.Returns([]);
_sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, _mockValidator);
_sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
@@ -55,7 +78,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -68,24 +91,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState()
{
// Arrange
LibraryMetadataProviderConfigurationEntity existingConfiguration = new()
{
Id = Guid.NewGuid(),
LibraryId = Guid.NewGuid(),
PluginId = Guid.NewGuid(),
IsEnabled = false,
Rank = 2,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = default,
UpdatedBy = default
};
LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create(
libraryId: Guid.NewGuid(),
pluginId: Guid.NewGuid(),
rank: 2,
isEnabled: false);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any<CancellationToken>())
.Returns(existingConfiguration);
_mockConfigurationRepository.UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -103,7 +120,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
_mockValidator.Validate(Arg.Any<SetLibraryMetadataProviderEnabledCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -112,4 +129,43 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any<LibraryMetadataProviderConfigurationEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Success> result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -3,14 +3,15 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings;
using Lumina.Application.Fixtures.Core.Plugins.Commands.UpdatePluginSettings;
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 System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings;
@@ -25,6 +26,7 @@ public class UpdatePluginSettingsCommandHandlerTests
private readonly IPluginRepository _mockPluginRepository;
private readonly IValidator<UpdatePluginSettingsCommand> _mockValidator;
private readonly UpdatePluginSettingsCommandHandler _sut;
private readonly UpdatePluginSettingsCommandFixture _updatePluginSettingsCommandFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePluginSettingsCommandHandlerTests"/> class.
@@ -50,7 +52,7 @@ public class UpdatePluginSettingsCommandHandlerTests
.Returns(Result.Updated);
// Act
Result<Success> result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
@@ -67,7 +69,7 @@ public class UpdatePluginSettingsCommandHandlerTests
_mockValidator.Validate(Arg.Any<UpdatePluginSettingsCommand>()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<Success> result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None);
Result<Success> result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
@@ -2,10 +2,15 @@
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.GetLibraryMetadataProviders;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
using System;
@@ -13,6 +18,7 @@ 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.GetLibraryMetadataProviders;
@@ -26,10 +32,14 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryMetadataProviderConfigurationRepository _mockLibraryMetadataProviderConfigurationRepository;
private readonly IPluginRepository _mockPluginRepository;
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ICurrentUserService _mockCurrentUserService;
private readonly IValidator<GetLibraryMetadataProvidersQuery> _mockValidator;
private readonly GetLibraryMetadataProvidersQueryHandler _sut;
private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly Guid _userId;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersQueryHandlerTests"/> class.
@@ -41,8 +51,34 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository);
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
_mockValidator = Substitute.For<IValidator<GetLibraryMetadataProvidersQuery>>();
_userId = Guid.NewGuid();
_sut = new GetLibraryMetadataProvidersQueryHandler(_mockUnitOfWork);
// 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<GetLibraryMetadataProvidersQuery>()).Returns([]);
_sut = new GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError()
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetLibraryMetadataProvidersQuery>()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError);
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -155,4 +191,41 @@ public class GetLibraryMetadataProvidersQueryHandlerTests
// Assert
Assert.True(result.IsFailure);
}
[Fact]
public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> 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 _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IReadOnlyList<LibraryMetadataProviderResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders;
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.GetLibraryMetadataProviders;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryMetadataProvidersQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryMetadataProvidersQueryValidatorTests
{
private readonly GetLibraryMetadataProvidersQueryValidator _validator = new();
private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new();
[Fact]
public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.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
GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -3,15 +3,15 @@ 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.Plugins;
using Lumina.Application.Common.Mapping.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings;
using Lumina.Contracts.Responses.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings;
using NSubstitute;
using System;
using System.Collections.Generic;
@@ -33,9 +33,11 @@ public class GetPluginSettingsQueryHandlerTests
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly IPluginManager _mockPluginManager;
private readonly IValidator<GetPluginSettingsQuery> _mockValidator;
private readonly GetPluginSettingsQueryHandler _sut;
private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new();
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPluginSettingsQueryHandlerTests"/> class.
@@ -46,8 +48,26 @@ public class GetPluginSettingsQueryHandlerTests
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockPluginManager = Substitute.For<IPluginManager>();
_mockValidator = Substitute.For<IValidator<GetPluginSettingsQuery>>();
_mockValidator.Validate(Arg.Any<GetPluginSettingsQuery>()).Returns([]);
_sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager);
_sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager, _mockValidator);
}
[Fact]
public async Task HandleAsync_WhenPluginIdIsEmpty_ShouldReturnValidationError()
{
// Arrange
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
_mockValidator.Validate(Arg.Any<GetPluginSettingsQuery>()).Returns([DomainErrors.Plugins.PluginIdCannotBeEmpty]);
// Act
Result<PluginSettingsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError);
await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
@@ -62,8 +82,8 @@ public class GetPluginSettingsQueryHandlerTests
IPlugin loadedPlugin = Substitute.For<IPlugin>();
loadedPlugin.GetSettingsSchema().Returns(
[
new PluginSettingDescriptorDto("key1", "Label 1", PluginSettingType.Text, "default"),
new PluginSettingDescriptorDto("key2", "Label 2", PluginSettingType.Select, null, ["a", "b"])
_pluginSettingDescriptorDtoFixture.Create(key: "key1", label: "Label 1", type: PluginSettingType.Text, defaultValue: "default"),
_pluginSettingDescriptorDtoFixture.Create(key: "key2", label: "Label 2", type: PluginSettingType.Select, allowedValues: ["a", "b"])
]);
_mockPluginManager.GetPlugin(query.PluginId).Returns(loadedPlugin);
IReadOnlyDictionary<string, string>? expectedSettings = JsonSerializer.Deserialize<Dictionary<string, string>>(plugin.SettingsJson!);
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings;
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.GetPluginSettings;
/// <summary>
/// Contains unit tests for the <see cref="GetPluginSettingsQueryValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPluginSettingsQueryValidatorTests
{
private readonly GetPluginSettingsQueryValidator _validator = new();
private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new();
[Fact]
public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
query = query with { PluginId = Guid.Empty };
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty);
}
[Fact]
public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError()
{
// Arrange
GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create();
// Act
List<Error> result = _validator.TestValidate(query);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -74,7 +74,7 @@ public class UpdateUserSettingsCommandHandlerTests
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -102,7 +102,7 @@ public class UpdateUserSettingsCommandHandlerTests
settings.UserId == _userId &&
settings.IsPaginationEnabled == command.IsPaginationEnabled &&
settings.ItemsPerPage == command.ItemsPerPage &&
settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker),
settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker),
Arg.Any<CancellationToken>());
await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any<UserSettingsEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
@@ -6,6 +6,7 @@ using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using NSubstitute;
@@ -28,6 +29,7 @@ public class GetUserSettingsQueryHandlerTests
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly GetUserSettingsQueryHandler _sut;
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly GetUserSettingsQueryFixture _getUserSettingsQueryFixture = new();
private readonly Guid _userId = Guid.NewGuid();
/// <summary>
@@ -49,7 +51,7 @@ public class GetUserSettingsQueryHandlerTests
public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings()
{
// Arrange
GetUserSettingsQuery query = new();
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId);
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(storedSettings));
@@ -62,14 +64,14 @@ public class GetUserSettingsQueryHandlerTests
Assert.Equal(storedSettings.UserId, result.Value.UserId);
Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled);
Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage);
Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker);
Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings()
{
// Arrange
GetUserSettingsQuery query = new();
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(null));
@@ -81,14 +83,14 @@ public class GetUserSettingsQueryHandlerTests
Assert.NotEqual(Guid.Empty, result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
}
[Fact]
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized()
{
// Arrange
GetUserSettingsQuery query = new();
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
@@ -104,7 +106,7 @@ public class GetUserSettingsQueryHandlerTests
public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError()
{
// Arrange
GetUserSettingsQuery query = new();
GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to retrieve user settings");
_mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any<CancellationToken>())
.Returns(error);
@@ -43,5 +43,6 @@
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Plugins.Contracts.Fixtures\Lumina.Plugins.Contracts.Fixtures.csproj" />
</ItemGroup>
</Project>
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
@@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class AddLibraryRequestTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
@@ -21,16 +23,16 @@ public class AddLibraryRequestTests
public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues()
{
// Arrange
AddLibraryRequest expected = new(
"Books",
"Book",
[@"C:\Media\Books"],
null,
true,
false,
true,
false,
true
AddLibraryRequest expected = _addLibraryRequestFixture.Create(
title: "Books",
libraryType: "Book",
contentLocations: [@"C:\Media\Books"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
@@ -45,20 +47,20 @@ public class AddLibraryRequestTests
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
{
// Arrange
AddLibraryRequest sut = new(
"Books",
"Book",
[@"C:\Media\Books"],
null,
true,
false,
true,
false,
true
AddLibraryRequest sut = _addLibraryRequestFixture.Create(
title: "Books",
libraryType: "Book",
contentLocations: [@"C:\Media\Books"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
(string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
(string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
// Assert
Assert.Equal(sut.Title, title);
@@ -67,7 +69,7 @@ public class AddLibraryRequestTests
Assert.Equal(sut.CoverImage, coverImage);
Assert.Equal(sut.IsEnabled, isEnabled);
Assert.Equal(sut.IsLocked, isLocked);
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management;
[ExcludeFromCodeCoverage]
public class UpdateLibraryRequestTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
@@ -24,18 +26,18 @@ public class UpdateLibraryRequestTests
// Arrange
Guid id = Guid.NewGuid();
Guid userId = Guid.NewGuid();
UpdateLibraryRequest expected = new(
id,
userId,
"Books",
"Book",
[@"C:\Media\Books"],
null,
true,
false,
true,
false,
true
UpdateLibraryRequest expected = _updateLibraryRequestFixture.Create(
id: id,
userId: userId,
title: "Books",
libraryType: "Book",
contentLocations: [@"C:\Media\Books"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
@@ -52,22 +54,22 @@ public class UpdateLibraryRequestTests
// Arrange
Guid id = Guid.NewGuid();
Guid userId = Guid.NewGuid();
UpdateLibraryRequest sut = new(
id,
userId,
"Books",
"Book",
[@"C:\Media\Books"],
null,
true,
false,
true,
false,
true
UpdateLibraryRequest sut = _updateLibraryRequestFixture.Create(
id: id,
userId: userId,
title: "Books",
libraryType: "Book",
contentLocations: [@"C:\Media\Books"],
coverImage: null,
isEnabled: true,
isLocked: false,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: true
);
// Act
(Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
(Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut;
// Assert
Assert.Equal(sut.Id, sutId);
@@ -78,7 +80,7 @@ public class UpdateLibraryRequestTests
Assert.Equal(sut.CoverImage, coverImage);
Assert.Equal(sut.IsEnabled, isEnabled);
Assert.Equal(sut.IsLocked, isLocked);
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
@@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings;
[ExcludeFromCodeCoverage]
public class UpdateUserSettingsRequestTests
{
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
@@ -21,7 +23,13 @@ public class UpdateUserSettingsRequestTests
public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues()
{
// Arrange
UpdateUserSettingsRequest expected = new(true, 50, true, true);
UpdateUserSettingsRequest expected = _updateUserSettingsRequestFixture.Create(
isPaginationEnabled: true,
itemsPerPage: 50,
shouldIgnoreThePrefixForAlphaPicker: true,
isThemeCachingEnabled: true,
shouldAggregateMetadataWhenMissing: false
);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -36,15 +44,22 @@ public class UpdateUserSettingsRequestTests
public void Deconstruct_WhenCalled_ShouldReturnAllProperties()
{
// Arrange
UpdateUserSettingsRequest sut = new(false, 25, false, false);
UpdateUserSettingsRequest sut = _updateUserSettingsRequestFixture.Create(
isPaginationEnabled: false,
itemsPerPage: 25,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: false,
shouldAggregateMetadataWhenMissing: false
);
// Act
(bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut;
(bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
// Assert
Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled);
Assert.Equal(sut.ItemsPerPage, itemsPerPage);
Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker);
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
}
}
@@ -58,7 +58,7 @@ public class LibraryResponseTests
LibraryResponse sut = _libraryResponseFixture.Create();
// Act
(Guid id, Guid userId, string title, LibraryType libraryType, List<string> contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut;
(Guid id, Guid userId, string title, LibraryType libraryType, List<string> contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut;
// Assert
Assert.Equal(sut.Id, id);
@@ -69,7 +69,7 @@ public class LibraryResponseTests
Assert.Equal(sut.CoverImage, coverImage);
Assert.Equal(sut.IsEnabled, isEnabled);
Assert.Equal(sut.IsLocked, isLocked);
Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb);
Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb);
Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories);
Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan);
Assert.Equal(sut.CreatedOnUtc, createdOnUtc);
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings;
[ExcludeFromCodeCoverage]
public class UserSettingsResponseTests
{
private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new();
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
@@ -23,7 +25,14 @@ public class UserSettingsResponseTests
{
// Arrange
Guid userId = Guid.NewGuid();
UserSettingsResponse expected = new(userId, true, 50, true, true);
UserSettingsResponse expected = _userSettingsResponseFixture.Create(
userId: userId,
isPaginationEnabled: true,
itemsPerPage: 50,
shouldIgnoreThePrefixForAlphaPicker: true,
isThemeCachingEnabled: true,
shouldAggregateMetadataWhenMissing: false
);
// Act
string json = JsonSerializer.Serialize(expected, _jsonOptions);
@@ -39,16 +48,24 @@ public class UserSettingsResponseTests
{
// Arrange
Guid userId = Guid.NewGuid();
UserSettingsResponse sut = new(userId, false, 25, false, false);
UserSettingsResponse sut = _userSettingsResponseFixture.Create(
userId: userId,
isPaginationEnabled: false,
itemsPerPage: 25,
shouldIgnoreThePrefixForAlphaPicker: false,
isThemeCachingEnabled: false,
shouldAggregateMetadataWhenMissing: false
);
// Act
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut;
(Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut;
// Assert
Assert.Equal(sut.UserId, sutUserId);
Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled);
Assert.Equal(sut.ItemsPerPage, itemsPerPage);
Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker);
Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker);
Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled);
Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing);
}
}
@@ -53,7 +53,7 @@ public class LibraryConfigurationTests
IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title));
IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType));
IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled));
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.DownloadMetadataFromWeb));
IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb));
// Assert
Assert.False(titleProperty.IsNullable);
@@ -52,7 +52,7 @@ public class UserSettingsConfigurationTests
IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId));
IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled));
IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage));
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.IgnoreThePrefixForAlphaPicker));
IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker));
// Assert
Assert.False(userIdProperty.IsNullable);
@@ -4,7 +4,10 @@ using Lumina.Application.Common.DataAccess.Entities.Common;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DTO.Filtering;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.DataAccess.Core.Repositories.Books;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
@@ -32,6 +35,13 @@ public class BookRepositoryTests
private readonly LuminaDbContext _mockContext;
private readonly BookRepository _sut;
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookRatingEntityFixture _bookRatingEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly IsbnEntityFixture _isbnEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new();
private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookRepositoryTests"/> class.
@@ -83,12 +93,12 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes()
{
// Arrange
TagEntity existingTag = new("Existing");
TagEntity existingTag = _tagEntityFixture.Create(name: "Existing");
_mockContext.Set<TagEntity>().Add(existingTag);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookEntityFixture.Create();
bookModel.Tags = [new("Existing"), new("New")];
bookModel.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")];
// Act
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
@@ -110,12 +120,12 @@ public class BookRepositoryTests
public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes()
{
// Arrange
GenreEntity existingGenre = new("Existing");
GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing");
_mockContext.Set<GenreEntity>().Add(existingGenre);
await _mockContext.SaveChangesAsync();
BookEntity bookModel = _bookEntityFixture.Create();
bookModel.Genres = [new("Existing"), new("New")];
bookModel.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")];
// Act
Result<Created> result = await _sut.InsertAsync(bookModel, CancellationToken.None);
@@ -168,9 +178,9 @@ public class BookRepositoryTests
{
// Arrange
BookEntity book = _bookEntityFixture.Create();
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
@@ -341,8 +351,8 @@ public class BookRepositoryTests
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -360,8 +370,8 @@ public class BookRepositoryTests
public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
BaseFilterDto filter = new();
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
BaseFilterDto filter = _baseFilterDtoFixture.Create();
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -375,8 +385,8 @@ public class BookRepositoryTests
public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError()
{
// Arrange
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = Guid.Empty };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -397,7 +407,7 @@ public class BookRepositoryTests
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
LibraryFilterDto filter = new() { LibraryId = libraryId };
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None);
@@ -425,8 +435,8 @@ public class BookRepositoryTests
_mockContext.Books.AddRange(fellowshipBook, towersBook);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship");
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -449,8 +459,8 @@ public class BookRepositoryTests
_mockContext.Books.AddRange(books);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 2 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -478,8 +488,8 @@ public class BookRepositoryTests
_mockContext.Books.AddRange(bookA, bookB);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None);
@@ -496,15 +506,15 @@ public class BookRepositoryTests
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create();
book.LibraryId = libraryId;
book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")];
book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")];
book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)];
book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)];
book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")];
book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")];
book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)];
book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)];
_mockContext.Books.Add(book);
await _mockContext.SaveChangesAsync();
PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 };
LibraryFilterDto filter = new() { LibraryId = libraryId };
PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10);
LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId);
// Act
Result<PaginatedResultDto<BookEntity>> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None);
@@ -1,12 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
@@ -23,6 +23,7 @@ public class LuminaDbContextTests : IDisposable
private readonly string _connectionString;
private readonly SqliteConnection _anchorConnection;
private readonly LuminaDbContext _context;
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContextTests"/> class.
@@ -46,7 +47,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
Assert.Equal(24, tableNames.Length);
Assert.Equal(25, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -63,6 +64,7 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("DirectoryScanFingerprints", tableNames);
Assert.Contains("Plugins", tableNames);
Assert.Contains("LibraryMetadataProviderConfigurations", tableNames);
Assert.Contains("LibraryArtworkProviderConfigurations", tableNames);
Assert.Contains("Tags", tableNames);
Assert.Contains("Genres", tableNames);
Assert.Contains("LibraryContentLocations", tableNames);
@@ -78,17 +80,10 @@ public class LuminaDbContextTests : IDisposable
{
// Arrange
_context.Database.EnsureCreated();
BookEntity book = new()
{
Id = Guid.NewGuid(),
LibraryId = Guid.NewGuid(),
Path = "/books/test.epub",
Title = "Test Book",
MetadataStatus = MetadataStatus.Pending,
CreatedOnUtc = DateTime.UtcNow,
CreatedBy = Guid.NewGuid(),
UpdatedBy = null
};
BookEntity book = _bookEntityFixture.Create(path: "/books/test.epub", title: "Test Book", includeMetadata: false);
book.MetadataStatus = MetadataStatus.Pending;
book.CreatedOnUtc = DateTime.UtcNow;
book.CreatedBy = Guid.NewGuid();
_context.Books.Add(book);
// Act
@@ -1,11 +1,7 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Time;
@@ -100,6 +96,26 @@ public class UnitOfWorkTests
await dbContext.Received(1).SaveChangesAsync(cancellationToken);
}
[Fact]
public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities()
{
// Arrange
DbContextOptions<LuminaDbContext> options = new DbContextOptionsBuilder<LuminaDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
LuminaDbContext dbContext = new(options);
UnitOfWork unitOfWork = new(dbContext);
dbContext.Roles.Add(new RoleEntity { Id = Guid.NewGuid(), RoleName = "TestRole" });
await dbContext.SaveChangesAsync(CancellationToken.None);
Assert.NotEmpty(dbContext.ChangeTracker.Entries());
// Act
unitOfWork.ClearTrackedEntities();
// Assert
Assert.Empty(dbContext.ChangeTracker.Entries());
}
[Fact]
public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories()
{
@@ -3,7 +3,6 @@ using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
@@ -14,7 +13,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
@@ -50,7 +48,7 @@ public class LibraryTests
coverImageSourcePath,
isEnabled: false,
isLocked: true,
downloadMetadataFromWeb: false,
canDownloadMetadataFromWeb: false,
shouldSaveMetadataInMediaDirectories: true,
shouldSkipUnchangedDirectoriesDuringScan: true,
scanIds);
@@ -64,7 +62,7 @@ public class LibraryTests
Assert.Equal(coverImageSourcePath, result.Value.CoverImage);
Assert.False(result.Value.IsEnabled);
Assert.True(result.Value.IsLocked);
Assert.False(result.Value.DownloadMetadataFromWeb);
Assert.False(result.Value.CanDownloadMetadataFromWeb);
Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories);
Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan);
Assert.Equal(scanIds, result.Value.ScanIds);
@@ -87,7 +85,7 @@ public class LibraryTests
null,
isEnabled: true,
isLocked: false,
downloadMetadataFromWeb: true,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
scanIds);
@@ -109,7 +107,7 @@ public class LibraryTests
null,
isEnabled: true,
isLocked: false,
downloadMetadataFromWeb: true,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
[]);
@@ -136,7 +134,7 @@ public class LibraryTests
null,
isEnabled: true,
isLocked: false,
downloadMetadataFromWeb: true,
canDownloadMetadataFromWeb: true,
shouldSaveMetadataInMediaDirectories: false,
shouldSkipUnchangedDirectoriesDuringScan: false,
[]);
@@ -5,7 +5,6 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -34,7 +33,8 @@ public class UserSettingsTests
Assert.Equal(userId, result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
}
[Fact]
@@ -48,7 +48,8 @@ public class UserSettingsTests
Assert.NotNull(result.Value.UserId);
Assert.True(result.Value.IsPaginationEnabled);
Assert.Equal(48, result.Value.ItemsPerPage);
Assert.False(result.Value.IgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(result.Value.ShouldAggregateMetadataWhenMissing);
}
[Fact]
@@ -72,15 +73,16 @@ public class UserSettingsTests
UserId userId = _userIdFixture.Create();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true);
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(userId, result.Value.UserId);
Assert.False(result.Value.IsPaginationEnabled);
Assert.Equal(24, result.Value.ItemsPerPage);
Assert.True(result.Value.IgnoreThePrefixForAlphaPicker);
Assert.True(result.Value.ShouldIgnoreThePrefixForAlphaPicker);
Assert.True(result.Value.IsThemeCachingEnabled);
Assert.True(result.Value.ShouldAggregateMetadataWhenMissing);
}
[Fact]
@@ -106,7 +108,7 @@ public class UserSettingsTests
UserId userId = _userIdFixture.Create();
// Act
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true);
Result<UserSettings> result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
// Assert
Assert.True(result.IsFailure);
@@ -120,14 +122,15 @@ public class UserSettingsTests
UserSettings userSettings = _userSettingsFixture.Create();
// Act
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false);
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true);
// Assert
Assert.False(result.IsFailure);
Assert.False(userSettings.IsPaginationEnabled);
Assert.Equal(12, userSettings.ItemsPerPage);
Assert.True(userSettings.IgnoreThePrefixForAlphaPicker);
Assert.True(userSettings.ShouldIgnoreThePrefixForAlphaPicker);
Assert.False(userSettings.IsThemeCachingEnabled);
Assert.True(userSettings.ShouldAggregateMetadataWhenMissing);
}
[Theory]
@@ -139,7 +142,7 @@ public class UserSettingsTests
UserSettings userSettings = _userSettingsFixture.Create();
// Act
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true);
Result<Updated> result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
// Assert
Assert.True(result.IsFailure);
@@ -1,9 +1,22 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
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.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
@@ -13,14 +26,17 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -45,6 +61,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
@@ -106,6 +129,51 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed()
{
// Arrange
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockUnitOfWork.Received(1).ClearTrackedEntities();
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
@@ -139,4 +207,371 @@ public class MediaLibraryScanMetadataEnrichmentJobTests
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description"));
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
// the book has no known identifiers of its own, so the findings of the first provider are fed to the second one
book.OpenLibraryId = null;
SetupSingleBookPage(book, firstPluginId, secondPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the second provider receives the lookup enriched with the open library Id discovered by the first provider
await secondProvider.Received(1).GetMetadataAsync(
Arg.Is<MetadataLookupDto>(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"),
Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
IMetadataProvider secondProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher"));
secondProvider.Name.Returns("Second Provider");
secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
secondProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId, secondPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata
await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>([
_configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1)
]));
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockBookRepository.Received(1).UpdateAsync(
Arg.Is<BookEntity>(entity => entity.MetadataStatus == MetadataStatus.Failed),
Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure(description: "Failed to get the artwork provider configurations"));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockBookRepository.Received(1).UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath()
{
// Arrange
Guid firstPluginId = Guid.NewGuid();
Guid artworkPluginId = Guid.NewGuid();
IMetadataProvider firstProvider = Substitute.For<IMetadataProvider>();
firstProvider.Name.Returns("First Provider");
firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
firstProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "First Title"));
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
IBookArtworkService mockBookArtworkService = Substitute.For<IBookArtworkService>();
mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg"));
ServiceCollection services = new();
services.AddKeyedSingleton(firstPluginId, firstProvider);
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
services.AddSingleton(mockBookArtworkService);
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, firstPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await mockBookArtworkService.Received(1).SaveBookArtworkAsync(
_libraryId.Value,
book.Id,
Arg.Any<string>(),
Arg.Any<string>(),
"First Title",
Arg.Any<ArtworkDto>(),
Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).UpdateAsync(
Arg.Is<BookEntity>(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess()
{
// Arrange
Guid localPluginId = Guid.NewGuid();
Guid webPluginId = Guid.NewGuid();
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
localProvider.Name.Returns("Local Provider");
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
localProvider.RequiresWebAccess.Returns(false);
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
webProvider.Name.Returns("Web Provider");
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
webProvider.RequiresWebAccess.Returns(true);
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, localPluginId, webPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched
await localProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess()
{
// Arrange
Guid localPluginId = Guid.NewGuid();
Guid webPluginId = Guid.NewGuid();
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
localProvider.Name.Returns("Local Provider");
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
localProvider.RequiresWebAccess.Returns(false);
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(includeTitle: false));
IMetadataProvider webProvider = Substitute.For<IMetadataProvider>();
webProvider.Name.Returns("Web Provider");
webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
webProvider.RequiresWebAccess.Returns(true);
webProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Web Title"));
SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false);
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, localPluginId, webPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the provider requiring access to the web is used when the library permits downloading data from the web
await webProvider.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess()
{
// Arrange
Guid localPluginId = Guid.NewGuid();
Guid artworkPluginId = Guid.NewGuid();
IMetadataProvider localProvider = Substitute.For<IMetadataProvider>();
localProvider.Name.Returns("Local Provider");
localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
localProvider.RequiresWebAccess.Returns(false);
localProvider.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_bookMetadataDtoFixture.Create(title: "Local Title"));
IArtworkProvider artworkProvider = Substitute.For<IArtworkProvider>();
artworkProvider.Name.Returns("Web Artwork Provider");
artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
artworkProvider.RequiresWebAccess.Returns(true);
artworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg"));
ServiceCollection services = new();
services.AddKeyedSingleton(localPluginId, localProvider);
services.AddKeyedSingleton(artworkPluginId, artworkProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
using ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
ILibraryRepository mockLibraryRepository = Substitute.For<ILibraryRepository>();
mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false)));
_mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository);
IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)]));
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub");
SetupSingleBookPage(book, localPluginId);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web
await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container.
/// </summary>
/// <param name="firstPluginId">The Id of the plugin providing the first metadata provider.</param>
/// <param name="firstProvider">The first metadata provider to resolve.</param>
/// <param name="secondPluginId">The Id of the plugin providing the second metadata provider, if any.</param>
/// <param name="secondProvider">The second metadata provider to resolve, if any.</param>
/// <param name="shouldAggregateMetadataWhenMissing">Whether the user settings enable aggregating metadata from multiple providers when fields are missing.</param>
private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false)
{
ServiceCollection services = new();
services.AddKeyedSingleton(firstPluginId, firstProvider);
if (secondPluginId is not null && secondProvider is not null)
services.AddKeyedSingleton(secondPluginId.Value, secondProvider);
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
// the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test
ServiceProvider realServiceProvider = services.BuildServiceProvider();
AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope();
_mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<UserSettingsEntity?>(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing)));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
}
/// <summary>
/// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers.
/// </summary>
/// <param name="book">The book the job must enrich.</param>
/// <param name="configuredPluginIds">The Ids of the plugins configured as metadata providers for the library.</param>
private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds)
{
_mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList()));
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]), Result.From<IReadOnlyList<BookEntity>>([]));
_mockBookRepository.UpdateAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
}
}
@@ -0,0 +1,332 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MetadataAggregator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MetadataAggregatorTests
{
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly TagDtoFixture _tagDtoFixture = new();
private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new();
[Fact]
public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false,
title: "First Title",
originalTitle: "First Original Title",
description: "First Description",
publisher: "First Publisher",
pageCount: 100,
format: BookFormat.Hardcover,
edition: "First Edition",
volumeNumber: 1,
asin: "FIRST-ASIN",
goodreadsId: "FIRST-GOODREADS",
lccn: "FIRST-LCCN",
oclcNumber: "FIRST-OCLC",
openLibraryId: "FIRST-OL",
libraryThingId: "FIRST-LT",
googleBooksId: "FIRST-GOOGLE",
barnesAndNobleId: "FIRST-BN",
appleBooksId: "FIRST-APPLE",
coverImagePath: "First Cover");
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false,
title: "Second Title",
originalTitle: "Second Original Title",
description: "Second Description",
publisher: "Second Publisher",
pageCount: 200,
format: BookFormat.Paperback,
edition: "Second Edition",
volumeNumber: 2,
asin: "SECOND-ASIN",
goodreadsId: "SECOND-GOODREADS",
lccn: "SECOND-LCCN",
oclcNumber: "SECOND-OCLC",
openLibraryId: "SECOND-OL",
libraryThingId: "SECOND-LT",
googleBooksId: "SECOND-GOOGLE",
barnesAndNobleId: "SECOND-BN",
appleBooksId: "SECOND-APPLE",
coverImagePath: "First Cover");
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("First Title", result.Title);
Assert.Equal("First Original Title", result.OriginalTitle);
Assert.Equal("First Description", result.Description);
Assert.Equal("First Publisher", result.Publisher);
Assert.Equal(100, result.PageCount);
Assert.Equal(BookFormat.Hardcover, result.Format);
Assert.Equal("First Edition", result.Edition);
Assert.Equal(1, result.VolumeNumber);
Assert.Equal("FIRST-ASIN", result.ASIN);
Assert.Equal("FIRST-GOODREADS", result.GoodreadsId);
Assert.Equal("FIRST-LCCN", result.LCCN);
Assert.Equal("FIRST-OCLC", result.OCLCNumber);
Assert.Equal("FIRST-OL", result.OpenLibraryId);
Assert.Equal("FIRST-LT", result.LibraryThingId);
Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId);
Assert.Equal("FIRST-BN", result.BarnesAndNobleId);
Assert.Equal("FIRST-APPLE", result.AppleBooksId);
Assert.Equal("First Cover", result.CoverImagePath);
}
[Fact]
public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, description: null, publisher: null, pageCount: null);
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: "Second Title", description: "Second Description", publisher: "Second Publisher", pageCount: 200);
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("Second Title", result.Title);
Assert.Equal("Second Description", result.Description);
Assert.Equal("Second Publisher", result.Publisher);
Assert.Equal(200, result.PageCount);
}
[Fact]
public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null);
BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null);
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Null(result.Title);
Assert.Null(result.Description);
Assert.Null(result.Publisher);
Assert.Null(result.PageCount);
Assert.Null(result.Format);
Assert.Null(result.Edition);
Assert.Null(result.VolumeNumber);
Assert.Null(result.Series);
}
[Fact]
public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false);
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false);
first = first with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: "US") };
second = second with { ReleaseInfo = _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: "UK", releaseVersion: "2.0") };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear);
Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate);
Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear);
Assert.Equal("US", result.ReleaseInfo.ReleaseCountry);
Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion);
}
[Fact]
public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001) };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate);
}
[Fact]
public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Null(result.ReleaseInfo);
}
[Fact]
public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(3, result.Genres!.Count);
Assert.Contains(result.Genres, genre => genre.Name == "Science fiction");
Assert.Contains(result.Genres, genre => genre.Name == "Space opera");
Assert.Contains(result.Genres, genre => genre.Name == "Fantasy");
}
[Fact]
public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(3, result.Tags!.Count);
Assert.Contains(result.Tags, tag => tag.Name == "Tag A");
Assert.Contains(result.Tags, tag => tag.Name == "Tag B");
Assert.Contains(result.Tags, tag => tag.Name == "Tag C");
}
[Fact]
public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(2, result.Isbns!.Count);
Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157");
Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152");
}
[Fact]
public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author"), _mediaContributorDtoFixture.Create("Translator B", "Translator")] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(2, result.Contributors!.Count);
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A");
Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B");
}
[Fact]
public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal(2, result.Ratings!.Count);
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre);
Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary);
}
[Fact]
public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A")], Genres = [_genreDtoFixture.Create(name: "Genre A")], Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("Tag A", Assert.Single(result.Tags!).Name);
Assert.Equal("Genre A", Assert.Single(result.Genres!).Name);
Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value);
Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName);
Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source);
}
[Fact]
public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag B")], Genres = [_genreDtoFixture.Create(name: "Genre B")], Isbns = [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], Contributors = [_mediaContributorDtoFixture.Create("Author B", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("Tag B", Assert.Single(result.Tags!).Name);
Assert.Equal("Genre B", Assert.Single(result.Genres!).Name);
Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value);
Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName);
Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source);
}
[Fact]
public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Null(result.Genres);
Assert.Null(result.Tags);
Assert.Null(result.Isbns);
Assert.Null(result.Contributors);
Assert.Null(result.Ratings);
}
[Fact]
public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English") };
BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch") };
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("en", result.Language!.LanguageCode);
}
}
@@ -43,6 +43,7 @@
<ProjectReference Include="..\..\..\src\Lumina.Infrastructure\Lumina.Infrastructure.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Domain.Fixtures\Lumina.Domain.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Application.Fixtures\Lumina.Application.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Contracts.Fixtures\Lumina.Contracts.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.Infrastructure.Fixtures\Lumina.Infrastructure.Fixtures.csproj" />
<ProjectReference Include="..\..\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj" />
</ItemGroup>
@@ -3,6 +3,7 @@ using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders;
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;
@@ -28,6 +29,7 @@ public class GetLibraryMetadataProvidersEndpointTests
private readonly IQueryHandler<GetLibraryMetadataProvidersQuery, Result<IReadOnlyList<LibraryMetadataProviderResponse>>> _mockHandler;
private readonly GetLibraryMetadataProvidersEndpoint _sut;
private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new();
private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryMetadataProvidersEndpointTests"/> class.
@@ -46,8 +48,8 @@ public class GetLibraryMetadataProvidersEndpointTests
CancellationToken cancellationToken = CancellationToken.None;
IReadOnlyList<LibraryMetadataProviderResponse> expectedResponses =
[
new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider A", true, 1),
new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider B", false, 2)
_libraryMetadataProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1),
_libraryMetadataProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2)
];
_mockHandler.HandleAsync(Arg.Any<GetLibraryMetadataProvidersQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponses));
@@ -3,6 +3,7 @@ using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.Plugins.Queries.GetPluginSettings;
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;
@@ -27,6 +28,7 @@ public class GetPluginSettingsEndpointTests
private readonly IQueryHandler<GetPluginSettingsQuery, Result<PluginSettingsResponse>> _mockHandler;
private readonly GetPluginSettingsEndpoint _sut;
private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new();
private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPluginSettingsEndpointTests"/> class.
@@ -43,10 +45,10 @@ public class GetPluginSettingsEndpointTests
// Arrange
GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
PluginSettingsResponse expectedResponse = new(
PluginId: request.PluginId,
Schema: [],
Settings: null
PluginSettingsResponse expectedResponse = _pluginSettingsResponseFixture.Create(
pluginId: request.PluginId,
schema: [],
settings: null
);
_mockHandler.HandleAsync(Arg.Any<GetPluginSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
@@ -92,7 +94,7 @@ public class GetPluginSettingsEndpointTests
GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetPluginSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new PluginSettingsResponse(request.PluginId, [], null)));
.Returns(Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null)));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
@@ -118,7 +120,7 @@ public class GetPluginSettingsEndpointTests
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(new PluginSettingsResponse(request.PluginId, [], null));
return Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null));
}, callInfo.Arg<CancellationToken>()));
// Act
@@ -2,6 +2,7 @@
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings;
using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings;
using Lumina.Contracts.Responses.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings;
@@ -24,6 +25,7 @@ public class GetUserSettingsEndpointTests
{
private readonly IQueryHandler<GetUserSettingsQuery, Result<UserSettingsResponse>> _mockHandler;
private readonly GetUserSettingsEndpoint _sut;
private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetUserSettingsEndpointTests"/> class.
@@ -39,7 +41,7 @@ public class GetUserSettingsEndpointTests
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false, true);
UserSettingsResponse expectedResponse = _userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
@@ -79,7 +81,7 @@ public class GetUserSettingsEndpointTests
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetUserSettingsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true)));
.Returns(Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false)));
// Act
await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken);
@@ -104,7 +106,7 @@ public class GetUserSettingsEndpointTests
operationStarted.SetResult(true);
await cancellationRequested.Task;
info.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true));
return Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false));
}, info.Arg<CancellationToken>()));
// Act
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings;
using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings;
using Lumina.Contracts.Requests.UsersManagement.Settings;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings;
@@ -23,6 +24,7 @@ public class UpdateUserSettingsEndpointTests
{
private readonly ICommandHandler<UpdateUserSettingsCommand, Result<Updated>> _mockHandler;
private readonly UpdateUserSettingsEndpoint _sut;
private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateUserSettingsEndpointTests"/> class.
@@ -37,7 +39,7 @@ public class UpdateUserSettingsEndpointTests
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 48, false, true);
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
@@ -54,7 +56,7 @@ public class UpdateUserSettingsEndpointTests
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 0, false, true);
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero.");
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
@@ -76,7 +78,7 @@ public class UpdateUserSettingsEndpointTests
public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler()
{
// Arrange
UpdateUserSettingsRequest request = new(true, 24, true, true);
UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false);
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<UpdateUserSettingsCommand>(), Arg.Any<CancellationToken>())
.Returns(Result.Updated);
@@ -89,7 +91,7 @@ public class UpdateUserSettingsEndpointTests
Arg.Is<UpdateUserSettingsCommand>(command =>
command.IsPaginationEnabled == request.IsPaginationEnabled &&
command.ItemsPerPage == request.ItemsPerPage &&
command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker &&
command.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker &&
command.IsThemeCachingEnabled == request.IsThemeCachingEnabled),
Arg.Is(cancellationToken));
}
@@ -112,7 +114,7 @@ public class UpdateUserSettingsEndpointTests
}, info.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false, true), cts.Token);
Task<IResult> operationTask = _sut.ExecuteAsync(_updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false), cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
@@ -38,6 +38,10 @@ public class UpdateUserSettingsEndpointTests
_sut = Factory.Create<UpdateUserSettingsEndpoint>(_mockApiHttpClient, CreateThemeCachePreferenceService());
}
/// <summary>
/// Creates a <see cref="ThemeCachePreferenceService"/> backed by an in-memory hybrid cache.
/// </summary>
/// <returns>The created theme cache preference service.</returns>
private static ThemeCachePreferenceService CreateThemeCachePreferenceService()
{
ServiceCollection services = new();
@@ -50,15 +54,15 @@ public class UpdateUserSettingsEndpointTests
{
// Arrange
UserSettingsDto request = _userSettingsDtoFixture.Create();
_mockApiHttpClient.PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
.Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
_mockApiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(Arg.Any<string>(), Arg.Any<UserSettingsDto>(), Arg.Any<CancellationToken>())
.Returns(new Web.Common.Requests.Common.EmptyRequest());
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
await _mockApiHttpClient.Received(1).PutAsync<Web.Common.Requests.Common.EmptyRequest, UserSettingsDto>(
ApiRoutes.Users.UPDATE_USER_SETTINGS,
Arg.Is<UserSettingsDto>(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled),
Arg.Any<CancellationToken>());