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

@@ -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);