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>