Renames project paths from Lumina to Nemera

This commit is contained in:
BinaryAlley committed 2026-11-27 15:34:43 +02:00
1 parent ce6fddb4c9
commit 0f659a4877
6450 files changed

No files matched your search

@@ -0,0 +1,160 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.Management.Progress;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Core.Time;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DependencyInjection;
/// <summary>
/// Contains unit tests for the <see cref="InfrastructureLayerServices"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class InfrastructureLayerServicesTests
{
[Fact]
public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterCoreInfrastructureServices()
{
// Arrange
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = CreateConfiguration();
// Act
services.AddInfrastructureLayerServices(configuration);
// Assert
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDateTimeProvider) && descriptor.ImplementationType == typeof(DateTimeProvider));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPlaybackFormatService) && descriptor.ImplementationType == typeof(PlaybackFormatService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginManager));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginSettingsStore));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventsQueue));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventPublisher));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanQueue));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanCancellationTracker));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibraryScanProgressNotifier));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IHostedService));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IConsumptionActivityAccessPolicy) && descriptor.ImplementationType == typeof(ConsumptionActivityAccessPolicy));
}
[Fact]
public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterAllValidatorsFromTheAssembly()
{
// Arrange
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = CreateConfiguration();
// Act
services.AddInfrastructureLayerServices(configuration);
// Assert
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<PluginsSettingsDto>));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<Lumina.Infrastructure.Common.Models.DTO.Configuration.CorsSettingsDto>));
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<Lumina.Infrastructure.Common.Models.DTO.Configuration.JwtSettingsDto>));
}
[Fact]
public void AddInfrastructureLayerServices_WhenCalled_ShouldGuardEveryOutboundHttpClientWithThePublicHostChecks()
{
// Arrange
IServiceCollection services = new ServiceCollection();
IConfiguration configuration = CreateConfiguration();
services.AddInfrastructureLayerServices(configuration);
// A plugin registers its typed client after the infrastructure layer, so the defaults must reach it too.
services.AddHttpClient("plugin-client");
using ServiceProvider serviceProvider = services.BuildServiceProvider();
IHttpMessageHandlerFactory httpMessageHandlerFactory = serviceProvider.GetRequiredService<IHttpMessageHandlerFactory>();
// Act
using HttpMessageHandler pluginClientHandler = httpMessageHandlerFactory.CreateHandler("plugin-client");
using HttpMessageHandler artworkClientHandler = httpMessageHandlerFactory.CreateHandler(NamedHttpClients.ARTWORK_DOWNLOAD);
// Assert
AssertUsesThePublicHostGuards(pluginClientHandler);
AssertUsesThePublicHostGuards(artworkClientHandler);
}
/// <summary>
/// Creates an in-memory configuration pointing the plugins directory to a non-existent folder, so no plugin assemblies are loaded.
/// </summary>
/// <returns>The created configuration.</returns>
private static IConfiguration CreateConfiguration()
{
Dictionary<string, string?> configurationValues = new()
{
[$"{PluginsSettingsDto.SECTION_NAME}:Directory"] = "non-existent-plugins-directory"
};
return new ConfigurationBuilder().AddInMemoryCollection(configurationValues).Build();
}
/// <summary>
/// Asserts that the provided handler pipeline validates the host of every request, follows redirects only to public HTTPS hosts, and connects only to an
/// address checked to be public.
/// </summary>
/// <param name="handler">The handler pipeline to check.</param>
private static void AssertUsesThePublicHostGuards(HttpMessageHandler handler)
{
List<DelegatingHandler> delegatingHandlers = GetDelegatingHandlers(handler);
int validationIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostValidationHandler);
int redirectIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostRedirectHandler);
// The validation handler must run before the redirect handler, because the redirect handler follows a redirect below the validation handler.
Assert.True(validationIndex >= 0, "The public host validation handler must be part of the outbound pipeline.");
Assert.True(redirectIndex > validationIndex, "The public host validation handler must run before the public host redirect handler.");
SocketsHttpHandler primaryHandler = Assert.IsType<SocketsHttpHandler>(GetPrimaryHandler(handler));
Assert.False(primaryHandler.AllowAutoRedirect);
Assert.NotNull(primaryHandler.ConnectCallback);
}
/// <summary>
/// Gets the delegating handlers of the provided handler pipeline, from the outermost to the innermost one.
/// </summary>
/// <param name="handler">The handler pipeline to walk.</param>
/// <returns>The delegating handlers of the pipeline.</returns>
private static List<DelegatingHandler> GetDelegatingHandlers(HttpMessageHandler handler)
{
List<DelegatingHandler> delegatingHandlers = [];
HttpMessageHandler currentHandler = handler;
while (currentHandler is DelegatingHandler delegatingHandler)
{
delegatingHandlers.Add(delegatingHandler);
currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler.");
}
return delegatingHandlers;
}
/// <summary>
/// Gets the primary, non delegating handler of the provided handler pipeline.
/// </summary>
/// <param name="handler">The handler pipeline to walk.</param>
/// <returns>The primary handler of the pipeline.</returns>
private static HttpMessageHandler GetPrimaryHandler(HttpMessageHandler handler)
{
HttpMessageHandler currentHandler = handler;
while (currentHandler is DelegatingHandler delegatingHandler)
currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler.");
return currentHandler;
}
}
@@ -0,0 +1,194 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
/// <summary>
/// Contains unit tests for the <see cref="DomainEventPublisher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainEventPublisherTests
{
public sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
public sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
private sealed class RecordingDomainEventHandler : IDomainEventHandler<TestDomainEvent>
{
private readonly List<string> _callLog;
private readonly string _handlerName;
public RecordingDomainEventHandler(List<string> callLog, string handlerName)
{
_callLog = callLog;
_handlerName = handlerName;
}
public ValueTask HandleAsync(TestDomainEvent domainEvent, CancellationToken cancellationToken)
{
_callLog.Add(_handlerName);
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Creates a publisher wired to a fresh service provider, optionally registering additional services.
/// </summary>
/// <param name="configureServices">Optional action used to register additional services into the provider.</param>
/// <returns>A domain event publisher resolved from the created provider.</returns>
private static IDomainEventPublisher CreatePublisher(Action<IServiceCollection>? configureServices = null)
{
IServiceCollection services = new ServiceCollection();
services.AddScoped<IDomainEventPublisher, DomainEventPublisher>();
configureServices?.Invoke(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetRequiredService<IDomainEventPublisher>();
}
/// <summary>
/// Creates a valid instance of <see cref="TestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static TestDomainEvent CreateTestDomainEvent()
{
return new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
/// <summary>
/// Creates a valid instance of <see cref="NestedTestDomainEvent"/>.
/// </summary>
/// <returns>The created domain event.</returns>
private static NestedTestDomainEvent CreateNestedTestDomainEvent()
{
return new NestedTestDomainEvent(Guid.NewGuid(), DateTime.UtcNow);
}
[Fact]
public async Task Publish_WhenHandlersAreRegistered_ShouldInvokeAllHandlersInOrder()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
List<string> callLog = [];
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "first"));
services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => new RecordingDomainEventHandler(callLog, "second"));
});
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
Assert.Equal(["first", "second"], callLog);
}
[Fact]
public async Task Publish_WhenNoHandlersAreRegisteredForTheEventType_ShouldNotThrow()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventPublisher publisher = CreatePublisher();
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
// Reaching this point without an exception means the publish was a no-op, as expected.
}
[Fact]
public async Task Publish_WhenOnlyAnotherEventTypeHasHandlers_ShouldNotInvokeThem()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => nestedHandler));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.DidNotReceive().HandleAsync(Arg.Any<NestedTestDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenHandlerThrows_ShouldPropagateTheException()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
InvalidOperationException expectedException = new("Test exception");
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
handler.HandleAsync(Arg.Any<TestDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(callInfo => throw expectedException);
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped<IDomainEventHandler<TestDomainEvent>>(_ => handler));
// Act
InvalidOperationException result = await Assert.ThrowsAsync<InvalidOperationException>(
() => publisher.PublishAsync(domainEvent, CancellationToken.None).AsTask());
// Assert
Assert.Same(expectedException, result);
}
[Fact]
public async Task Publish_WhenHandlerPublishesAnotherEvent_ShouldInvokeNestedHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
NestedTestDomainEvent nestedDomainEvent = CreateNestedTestDomainEvent();
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventHandler<NestedTestDomainEvent> nestedHandler = Substitute.For<IDomainEventHandler<NestedTestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services =>
{
services.AddScoped(_ => handler);
services.AddScoped(_ => nestedHandler);
});
handler.HandleAsync(domainEvent, Arg.Any<CancellationToken>())
.Returns(callInfo => publisher.PublishAsync(nestedDomainEvent, callInfo.Arg<CancellationToken>()));
// Act
await publisher.PublishAsync(domainEvent, CancellationToken.None);
// Assert
await nestedHandler.Received(1).HandleAsync(nestedDomainEvent, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Publish_WhenCancellationRequested_ShouldPassTokenToHandlers()
{
// Arrange
TestDomainEvent domainEvent = CreateTestDomainEvent();
using CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
IDomainEventHandler<TestDomainEvent> handler = Substitute.For<IDomainEventHandler<TestDomainEvent>>();
IDomainEventPublisher publisher = CreatePublisher(services => services.AddScoped(_ => handler));
// Act
await publisher.PublishAsync(domainEvent, cancellationToken);
// Assert
await handler.Received(1).HandleAsync(domainEvent, Arg.Is(cancellationToken));
}
[Fact]
public async Task Publish_WhenDomainEventIsNull_ShouldThrowArgumentNullException()
{
// Arrange
IDomainEventPublisher publisher = CreatePublisher();
// Act
ArgumentNullException result = await Assert.ThrowsAsync<ArgumentNullException>(() => publisher.PublishAsync(null!, CancellationToken.None).AsTask());
// Assert
Assert.Equal("domainEvent", result.ParamName);
}
}
@@ -0,0 +1,109 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Infrastructure.Common.DomainEvents;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents;
/// <summary>
/// Contains unit tests for the <see cref="DomainEventsQueue"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DomainEventsQueueTests
{
private readonly DomainEventsQueue _sut = new();
[Fact]
public void TryDequeue_WhenQueueIsEmpty_ShouldReturnFalse()
{
// Act
bool result = _sut.TryDequeue(out IDomainEvent domainEvent);
// Assert
Assert.False(result);
Assert.Null(domainEvent);
}
[Fact]
public void Enqueue_WhenCalled_ShouldDequeueTheSameDomainEvent()
{
// Arrange
TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(domainEvent);
bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent);
// Assert
Assert.True(result);
Assert.Same(domainEvent, dequeuedEvent);
}
[Fact]
public void Enqueue_WhenCalledMultipleTimes_ShouldDequeueInFifoOrder()
{
// Arrange
TestDomainEvent firstEvent = new(Guid.NewGuid(), DateTime.UtcNow);
TestDomainEvent secondEvent = new(Guid.NewGuid(), DateTime.UtcNow);
TestDomainEvent thirdEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(firstEvent);
_sut.Enqueue(secondEvent);
_sut.Enqueue(thirdEvent);
_sut.TryDequeue(out IDomainEvent firstDequeued);
_sut.TryDequeue(out IDomainEvent secondDequeued);
_sut.TryDequeue(out IDomainEvent thirdDequeued);
// Assert
Assert.Same(firstEvent, firstDequeued);
Assert.Same(secondEvent, secondDequeued);
Assert.Same(thirdEvent, thirdDequeued);
}
[Fact]
public void Enqueue_WhenCalledWithMultipleEventTypes_ShouldDequeueAllTypes()
{
// Arrange
TestDomainEvent testEvent = new(Guid.NewGuid(), DateTime.UtcNow);
NestedTestDomainEvent nestedEvent = new(Guid.NewGuid(), DateTime.UtcNow);
// Act
_sut.Enqueue(testEvent);
_sut.Enqueue(nestedEvent);
_sut.TryDequeue(out IDomainEvent firstDequeued);
_sut.TryDequeue(out IDomainEvent secondDequeued);
// Assert
Assert.Same(testEvent, firstDequeued);
Assert.Same(nestedEvent, secondDequeued);
}
[Fact]
public void TryDequeue_WhenAllEventsWereDequeued_ShouldReturnFalseOnNextCall()
{
// Arrange
TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow);
_sut.Enqueue(domainEvent);
// Act
_sut.TryDequeue(out _);
bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent);
// Assert
Assert.False(result);
Assert.Null(dequeuedEvent);
}
/// <summary>
/// Test domain event used by the queue tests.
/// </summary>
private sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
/// <summary>
/// A second test domain event used by the queue tests.
/// </summary>
private sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent;
}
@@ -0,0 +1,275 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Plugins.Contracts.Common.Http;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostConnectionGuard"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostConnectionGuardTests
{
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Fact]
public void CreatePrimaryHandler_WhenCalled_ShouldDisableAutomaticRedirectsAndInstallTheConnectGuard()
{
// Arrange
PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress]);
// Act
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
// Assert
Assert.False(handler.AllowAutoRedirect);
Assert.False(handler.UseProxy);
Assert.NotNull(handler.ConnectCallback);
// The callback behavior itself is covered by CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest.
}
[Fact]
public async Task ConnectAsync_WhenTheHostResolvesToOnePrivateAddress_ShouldThrowWithoutConnecting()
{
// Arrange
PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]);
// Act
Task Act()
{
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", 443, request: null, NullLogger.Instance, CancellationToken.None).AsTask();
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
}
[Fact]
public async Task ConnectAsync_WhenTheRequestUriHasAUnicodeIdnHostAndTheConnectionUsesThePunycodeHost_ShouldValidateTheResolvedAddress()
{
// Arrange
// Uri.Host keeps the Unicode spelling of an internationalized name, while the connection authority uses its punycode spelling. The two must never be
// compared to decide whether a connection goes to a proxy, because an attacker controlled name could otherwise skip the address check.
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
using HttpRequestMessage request = new(HttpMethod.Get, "https://bücher.example/cover.jpg");
// Act
Task Act()
{
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "xn--bcher-kva.example", 1, request, NullLogger.Instance, CancellationToken.None).AsTask();
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
Assert.DoesNotContain("127.0.0.1", exception.Message);
}
[Fact]
public async Task ConnectAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrowWithoutConnecting()
{
// Arrange
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
using HttpRequestMessage request = new(HttpMethod.Get, "http://other.internal.example.com/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
// Act
Task Act()
{
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "other.internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask();
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
}
[Fact]
public async Task ConnectAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrowWithoutConnecting()
{
// Arrange
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
// Act
Task Act()
{
return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask();
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason);
}
[Fact]
public async Task ConnectAsync_WhenTheFirstAddressIsUnreachable_ShouldConnectToTheNextAddress()
{
// Arrange
using TcpListener listener = new(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
// 10.0.0.1 is a private address that no test service listens on, so the loopback address wins the staggered race.
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("10.0.0.1"), IPAddress.Loopback]);
using HttpRequestMessage request = new(HttpMethod.Get, "http://mixed.example.com/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "mixed.example.com");
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
// Act
Task<Stream> connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask();
(TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource);
using (acceptedClient)
using (stream)
{
// Assert
Assert.True(stream.CanWrite);
}
}
[Fact]
public async Task CreatePrimaryHandler_WhenTheConnectPolicyRejectsTheAddress_ShouldWrapThePolicyRejectionAsAConnectionError()
{
// Arrange
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
using HttpClient client = new(handler);
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
// Act
Task Act()
{
return client.GetAsync("http://internal.example.com/", cancellationTokenSource.Token);
}
// Assert
HttpRequestException exception = await Assert.ThrowsAsync<HttpRequestException>(Act);
Assert.Equal(HttpRequestError.ConnectionError, exception.HttpRequestError);
PublicHostRejectedException innerException = Assert.IsType<PublicHostRejectedException>(exception.InnerException);
Assert.Equal(HttpRequestError.ConfigurationLimitExceeded, innerException.HttpRequestError);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, innerException.RejectionReason);
}
[Fact]
public async Task CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest()
{
// Arrange
using TcpListener listener = new(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance);
using HttpClient client = new(handler);
using HttpRequestMessage request = new(HttpMethod.Get, $"http://internal.example.com:{port}/");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
// Act
Task<HttpResponseMessage> requestTask = client.SendAsync(request, cancellationTokenSource.Token);
Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask();
try
{
Task firstCompletedTask = await Task.WhenAny(requestTask, acceptTask);
// Await the request first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout.
if (firstCompletedTask == requestTask)
await requestTask;
using TcpClient acceptedClient = await acceptTask;
using NetworkStream stream = acceptedClient.GetStream();
byte[] responseBytes = Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
await stream.WriteAsync(responseBytes, cancellationTokenSource.Token);
using HttpResponseMessage response = await requestTask;
// Assert
// The connect callback resolved the host through the validator and read the allowed private host from the initial request message, because
// without that option the loopback address would have been rejected and the connection would never have been accepted.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
finally
{
cancellationTokenSource.Cancel();
}
}
[Fact]
public async Task ConnectAsync_WhenTheRequestAllowsPrivateEndPoints_ShouldConnectToThePrivateAddress()
{
// Arrange
using TcpListener listener = new(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]);
using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com");
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10));
// Act
Task<Stream> connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask();
(TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource);
using (acceptedClient)
using (stream)
{
// Assert
Assert.True(stream.CanWrite);
}
}
/// <summary>
/// Accepts the connection made by <paramref name="connectTask"/>, surfacing a connection failure instead of waiting for the accept timeout.
/// </summary>
/// <param name="listener">The listener that accepts the connection.</param>
/// <param name="connectTask">The task that establishes the connection.</param>
/// <param name="cancellationTokenSource">The cancellation token source that bounds the accept.</param>
/// <returns>The accepted client and the established stream.</returns>
private static async Task<(TcpClient AcceptedClient, Stream Stream)> AcceptConnectionAsync(TcpListener listener, Task<Stream> connectTask, CancellationTokenSource cancellationTokenSource)
{
Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask();
try
{
Task firstCompletedTask = await Task.WhenAny(connectTask, acceptTask).ConfigureAwait(false);
// Await the connect task first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout.
if (firstCompletedTask == connectTask)
await connectTask.ConfigureAwait(false);
TcpClient acceptedClient = await acceptTask.ConfigureAwait(false);
Stream stream = await connectTask.ConfigureAwait(false);
return (acceptedClient, stream);
}
catch
{
cancellationTokenSource.Cancel();
try
{
await acceptTask.ConfigureAwait(false);
}
catch
{
// The accept was canceled because the connection failed; its exception must not mask the connection failure.
}
throw;
}
}
/// <summary>
/// Creates a <see cref="PublicHostValidator"/> whose host name resolution is replaced by the provided resolver.
/// </summary>
/// <param name="addressResolver">The resolver that produces the addresses of a host name.</param>
/// <returns>The created validator.</returns>
private static PublicHostValidator CreateValidator(Func<string, IPAddress[]> addressResolver)
{
return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host)));
}
}
@@ -0,0 +1,427 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Plugins.Contracts.Common.Http;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostRedirectHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostRedirectHandlerTests
{
private const string PRIVATE_HOST = "internal.example.com";
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToAPublicHttpsHost_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/download/mbid-1/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
// Act
HttpResponseMessage response = await client.GetAsync("https://coverartarchive.org/release/1");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host);
}
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToAPrivateHostName_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Theory]
[InlineData("http://archive.org/index.json")] // A downgrade of a trusted host to plain HTTP.
[InlineData("https://127.0.0.1/index.json")] // The IPv4 loopback address.
[InlineData("https://localhost/index.json")] // The loopback host name.
[InlineData("https://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
[InlineData("https://10.0.0.5/index.json")] // A private class A address.
[InlineData("https://192.168.1.10/index.json")] // A private class C address.
public async Task SendAsync_WhenTheResponseRedirectsToADisallowedTarget_ShouldThrow(string location)
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri(location);
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsAndRedirectsToAPrivateHost_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
Assert.Equal(PRIVATE_HOST, innerHandler.Requests[1].RequestUri!.Host);
}
[Fact]
public async Task SendAsync_WhenARequestWithABodyIsRedirected_ShouldReturnTheRedirectResponseWithoutFollowingIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Post, "https://coverartarchive.org/release/1");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestIsRedirectedTooManyTimes_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/loop/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
Assert.Equal(6, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestDisablesRedirectFollowing_ShouldReturnTheRedirectResponseWithoutFollowingIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/release/1");
request.Options.Set(OutboundRequestOptions.FollowRedirects, false);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode);
Assert.Equal("https://archive.org/index.json", response.Headers.Location!.AbsoluteUri);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRedirectPointsAtAnotherPrivateHostThanTheAllowedOne_ShouldThrow()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://another.internal.example.com/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
Task Act()
{
return client.SendAsync(request);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenARedirectCrossesOrigins_ShouldNotForwardCredentialsOrHopByHopHeaders()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
request.Headers.TryAddWithoutValidation("Proxy-Authorization", "Basic secret");
request.Headers.Host = "coverartarchive.org";
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=5");
request.Headers.TryAddWithoutValidation("TE", "trailers");
request.Headers.TryAddWithoutValidation("Upgrade", "h2c");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
Assert.Null(redirectedRequest.Headers.Authorization);
Assert.False(redirectedRequest.Headers.Contains("Cookie"));
Assert.False(redirectedRequest.Headers.Contains("Proxy-Authorization"));
Assert.Null(redirectedRequest.Headers.Host);
Assert.False(redirectedRequest.Headers.Contains("Connection"));
Assert.False(redirectedRequest.Headers.Contains("Keep-Alive"));
Assert.False(redirectedRequest.Headers.Contains("TE"));
Assert.False(redirectedRequest.Headers.Contains("Upgrade"));
Assert.Contains("application/json", redirectedRequest.Headers.Accept.ToString());
}
[Fact]
public async Task SendAsync_WhenARedirectStaysOnTheSameOrigin_ShouldKeepCredentialsButDropHopByHopHeaders()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://coverartarchive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret");
request.Headers.TryAddWithoutValidation("Cookie", "session=secret");
request.Headers.TryAddWithoutValidation("Connection", "keep-alive");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
HttpRequestMessage redirectedRequest = innerHandler.Requests[1];
Assert.Equal("Bearer secret", redirectedRequest.Headers.Authorization!.ToString());
string cookieHeader = Assert.Single(redirectedRequest.Headers.GetValues("Cookie"));
Assert.Equal("session=secret", cookieHeader);
Assert.False(redirectedRequest.Headers.Contains("Connection"));
}
[Fact]
public async Task SendAsync_WhenAHeadRequestIsRedirected_ShouldFollowIt()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex == 1)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("https://archive.org/index.json");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Head, "https://coverartarchive.org/release/1");
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenAnAllowedPrivateHostRedirectsToItselfAcrossMultipleHops_ShouldKeepThePermission()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
if (callIndex <= 2)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri(callIndex == 1 ? $"https://{PRIVATE_HOST}/second" : $"https://{PRIVATE_HOST}/third");
return redirect;
}
return new HttpResponseMessage(HttpStatusCode.OK);
});
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(3, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheResponseRedirectsToPlainHttp_ShouldThrowAPublicHostRejectedException()
{
// Arrange
StubHttpMessageHandler innerHandler = new((request, callIndex) =>
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri("http://archive.org/index.json");
return redirect;
});
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync("https://coverartarchive.org/release/1");
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.RedirectSchemeNotHttps, exception.RejectionReason);
Assert.Equal(1, innerHandler.CallCount);
}
/// <summary>
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
/// </summary>
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
/// <returns>The created client.</returns>
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
{
PublicHostValidator publicHostValidator = new((host, cancellationToken) =>
Task.FromResult<IPAddress[]>(host.Contains("internal.example.com", StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
PublicHostRedirectHandler handler = new(publicHostValidator, NullLogger<PublicHostRedirectHandler>.Instance) { InnerHandler = innerHandler };
return new HttpClient(handler);
}
/// <summary>
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
private int _callCount;
/// <summary>
/// Gets the requests that were sent through the handler.
/// </summary>
public List<HttpRequestMessage> Requests { get; } = [];
/// <summary>
/// Gets the number of requests that were sent through the handler.
/// </summary>
public int CallCount => _callCount;
/// <summary>
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
{
_responseFactory = responseFactory;
}
/// <summary>
/// Sends the provided request, producing its response through the configured factory.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response produced for the request.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
int callIndex = Interlocked.Increment(ref _callCount);
Requests.Add(request);
return Task.FromResult(_responseFactory(request, callIndex));
}
}
}
@@ -0,0 +1,240 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using Lumina.Plugins.Contracts.Common.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostValidationHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostValidationHandlerTests
{
private const string PRIVATE_HOST = "internal.example.com";
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Fact]
public async Task SendAsync_WhenTheHostIsPublic_ShouldSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
using HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Theory]
[InlineData("http://127.0.0.1/cover.jpg")] // The IPv4 loopback address.
[InlineData("http://localhost/cover.jpg")] // The loopback host name.
[InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address.
[InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint.
[InlineData("http://10.0.0.5/cover.jpg")] // A private class A address.
[InlineData("http://172.16.0.1/cover.jpg")] // A private class B address.
[InlineData("http://192.168.1.10/cover.jpg")] // A private class C address.
public async Task SendAsync_WhenTheHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url)
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync(url);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
// Act
Task Act()
{
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason);
Assert.Contains(PRIVATE_HOST, exception.Message);
Assert.DoesNotContain("10.0.0.5", exception.Message);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostCannotBeResolved_ShouldThrowAPublicHostResolutionException()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
PublicHostValidator validator = new((host, cancellationToken) => throw new SocketException((int)SocketError.HostNotFound));
PublicHostValidationHandler handler = new(validator, NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
using HttpClient client = new(handler);
// Act
Task Act()
{
return client.GetAsync("https://missing.example.com/cover.jpg");
}
// Assert
PublicHostResolutionException exception = await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
Assert.Equal(HttpRequestError.NameResolutionError, exception.HttpRequestError);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheHostIsRejected_ShouldLogAWarning()
{
// Arrange
ILogger<PublicHostValidationHandler> mockLogger = Substitute.For<ILogger<PublicHostValidationHandler>>();
mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler };
using HttpClient client = new(handler);
// Act
Task Act()
{
return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg");
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForTheHost_ShouldSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST);
// Act
using HttpResponseMessage response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(1, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForAnotherHost_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
using HttpClient client = CreateClient(innerHandler);
using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg");
request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "another.internal.example.com");
// Act
Task Act()
{
return client.SendAsync(request);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(0, innerHandler.CallCount);
}
[Fact]
public async Task SendAsync_WhenTheRequestHasNoAbsoluteUri_ShouldThrowAndNotSendTheRequest()
{
// Arrange
StubHttpMessageHandler innerHandler = new();
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
using HttpMessageInvoker invoker = new(handler);
// Act
Task Act()
{
return invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/relative"), CancellationToken.None);
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.RequestHasNoAbsoluteUri, exception.RejectionReason);
Assert.Equal(0, innerHandler.CallCount);
}
/// <summary>
/// Creates an <see cref="HttpClient"/> whose requests are sent through the handler under test, wrapping the provided inner handler.
/// </summary>
/// <param name="innerHandler">The handler that answers the requests that reach the network.</param>
/// <returns>The created client.</returns>
private static HttpClient CreateClient(HttpMessageHandler innerHandler)
{
PublicHostValidationHandler handler = new(CreateValidator(), NullLogger<PublicHostValidationHandler>.Instance) { InnerHandler = innerHandler };
return new HttpClient(handler);
}
/// <summary>
/// Creates a <see cref="PublicHostValidator"/> that classifies <see cref="PRIVATE_HOST"/> as private and every other host name as public.
/// </summary>
/// <returns>The created validator.</returns>
private static PublicHostValidator CreateValidator()
{
return new PublicHostValidator((host, cancellationToken) =>
Task.FromResult<IPAddress[]>(string.Equals(host, PRIVATE_HOST, StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress]));
}
/// <summary>
/// Test HTTP message handler that answers every request with a successful response and records how many requests were sent to it.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StubHttpMessageHandler : HttpMessageHandler
{
private int _callCount;
/// <summary>
/// Gets the number of requests that were sent through the handler.
/// </summary>
public int CallCount => _callCount;
/// <summary>
/// Sends the provided request, producing a successful response.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response produced for the request.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _callCount);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
}
@@ -0,0 +1,502 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Networking;
using Lumina.Infrastructure.Common.Networking;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Networking;
/// <summary>
/// Contains unit tests for the <see cref="PublicHostValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PublicHostValidatorTests
{
private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34");
[Theory]
[InlineData("8.8.8.8")] // A public IPv4 address.
[InlineData("1.1.1.1")] // A public IPv4 address.
[InlineData("172.15.0.1")] // The address just below the private class B range.
[InlineData("172.32.0.1")] // The address just above the private class B range.
[InlineData("100.63.255.255")] // The address just below the carrier grade NAT range.
[InlineData("100.128.0.1")] // The address just above the carrier grade NAT range.
[InlineData("2606:4700:4700::1111")] // A public IPv6 address.
[InlineData("[2606:4700:4700::1111]")] // A public IPv6 address, bracketed like a URI host.
[InlineData("::ffff:93.184.216.34")] // An IPv4-mapped public IPv4 address.
public async Task ValidateHostAsync_WhenTheHostIsAPublicAddress_ShouldReturnTrue(string host)
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Theory]
[InlineData("")] // An empty host.
[InlineData(" ")] // Only white space.
[InlineData("localhost")] // The loopback host name.
[InlineData("LOCALHOST")] // The loopback host name, upper cased.
[InlineData("127.0.0.1")] // The IPv4 loopback address.
[InlineData("::1")] // The IPv6 loopback address.
[InlineData("[::1]")] // The IPv6 loopback address, bracketed like a URI host.
[InlineData("0.0.0.0")] // The unspecified IPv4 address.
[InlineData("[::]")] // The unspecified IPv6 address.
[InlineData("169.254.169.254")] // The link local cloud metadata endpoint.
[InlineData("10.0.0.5")] // A private class A address.
[InlineData("::ffff:10.0.0.5")] // A private class A address, in its IPv4-mapped IPv6 form.
[InlineData("172.16.0.1")] // The lower bound of the private class B range.
[InlineData("172.31.255.255")] // The upper bound of the private class B range.
[InlineData("192.168.1.10")] // A private class C address.
[InlineData("100.64.0.1")] // The lower bound of the carrier grade NAT range.
[InlineData("100.127.255.255")] // The upper bound of the carrier grade NAT range.
[InlineData("192.0.2.10")] // The TEST-NET-1 documentation range.
[InlineData("198.18.0.1")] // The benchmarking range.
[InlineData("198.51.100.10")] // The TEST-NET-2 documentation range.
[InlineData("203.0.113.10")] // The TEST-NET-3 documentation range.
[InlineData("224.0.0.1")] // The multicast range.
[InlineData("240.0.0.1")] // The reserved range.
[InlineData("255.255.255.255")] // The broadcast address.
[InlineData("fc00::1")] // The IPv6 unique local range.
[InlineData("fd00:ec2::254")] // The AWS IMDSv6 endpoint, which lives in a unique local range.
[InlineData("fe80::1")] // The IPv6 link local range.
[InlineData("2001:db8::1")] // The IPv6 documentation range.
[InlineData("::127.0.0.1")] // An IPv4 compatible IPv6 address.
[InlineData("64:ff9b:1::1")] // The local use NAT64 prefix.
[InlineData("2002::1")] // The IPv6 6to4 range.
[InlineData("64:ff9b::1")] // The IPv6 NAT64 prefix.
[InlineData("100::1")] // The IPv6 discard only range.
[InlineData("ff02::1")] // The IPv6 multicast range.
public async Task ValidateHostAsync_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host)
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIPv4MappedPrivateAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("::ffff:10.0.0.5", allowedPrivateHost: "::ffff:10.0.0.5", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToPublicAddresses_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("93.184.216.35")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToBothPublicAndPrivateAddresses_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("192.168.1.10")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("mixed.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameCannotBeResolved_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameIsMalformed_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new ArgumentException("The host is malformed."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("malformed host", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostNameResolvesToNoAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => []);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("empty.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenCancellationIsRequested_ShouldThrowOperationCanceledException()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new OperationCanceledException());
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task Act()
{
return sut.ValidateHostAsync("example.com", allowedPrivateHost: null, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenThePublicHostNameResolvesToAddresses_ShouldReturnTheirEndPoints()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, s_publicAddress]);
IPAddress expectedAddress = s_publicAddress;
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(443, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("mixed.example.com", 80, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostIsAnIPv4MappedIPv6Address_ShouldReturnItsIPv4EndPoint()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved."));
IPAddress expectedAddress = IPAddress.Parse("93.184.216.34");
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("::ffff:93.184.216.34", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(443, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostCannotBeResolved_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound));
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("missing.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToNoAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => []);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("empty.example.com", 443, allowedPrivateHost: null, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostResolutionException>(Act);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenAnotherHostResolvesToOnePrivateAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("other.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsLocalhost_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("The loopback host name must not be resolved."));
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("localhost", allowedPrivateHost: "localhost", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIdnNameAndTheConnectionUsesItsPunycodeSpelling_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("192.168.1.10")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("xn--bcher-kva.example", allowedPrivateHost: "bücher.example", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAnIPv6UniqueLocalAddress_ShouldReturnTrue()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fc00::1")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.True(result.IsAllowed);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAwsMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fd00:ec2::254")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, result.RejectionReason);
}
[Fact]
public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAlibabaMetadataAddress_ShouldReturnFalse()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("100.100.100.200")]);
// Act
PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
Assert.False(result.IsAllowed);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnItsEndPoint()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
IPAddress expectedAddress = IPAddress.Parse("10.0.0.5");
// Act
IReadOnlyList<IPEndPoint> result = await sut.ResolveEndPointsAsync("internal.example.com", 8080, allowedPrivateHost: "internal.example.com", CancellationToken.None);
// Assert
IPEndPoint endPoint = Assert.Single(result);
Assert.Equal(expectedAddress, endPoint.Address);
Assert.Equal(8080, endPoint.Port);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("other.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrow()
{
// Arrange
PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]);
// Act
Task Act()
{
return sut.ResolveEndPointsAsync("internal.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None);
}
// Assert
PublicHostRejectedException exception = await Assert.ThrowsAsync<PublicHostRejectedException>(Act);
Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason);
}
[Fact]
public async Task ValidateHostAsync_WhenTheSameHostIsCheckedTwice_ShouldResolveItOnlyOnce()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
return Task.FromResult<IPAddress[]>([s_publicAddress]);
});
// Act
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
[Fact]
public async Task ResolveEndPointsAsync_WhenTheHostWasAlreadyChecked_ShouldReuseTheResolution()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
return Task.FromResult<IPAddress[]>([s_publicAddress]);
});
// Act
await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
[Fact]
public async Task ValidateHostAsync_WhenTheHostCannotBeResolvedTwice_ShouldCacheTheFailureBriefly()
{
// Arrange
int resolutionCount = 0;
PublicHostValidator sut = new((host, cancellationToken) =>
{
resolutionCount++;
throw new SocketException((int)SocketError.HostNotFound);
});
// Act
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None);
// Assert
Assert.Equal(1, resolutionCount);
}
/// <summary>
/// Creates a <see cref="PublicHostValidator"/> whose host name resolution is replaced by the provided resolver.
/// </summary>
/// <param name="addressResolver">The resolver that produces the addresses of a host name.</param>
/// <returns>The created validator.</returns>
private static PublicHostValidator CreateValidator(Func<string, IPAddress[]> addressResolver)
{
return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host)));
}
}
@@ -0,0 +1,121 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="ExceptionUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ExceptionUtilitiesTests
{
[Fact]
public void AggregateMessages_WhenCalledWithNestedException_ShouldConcatenateAllMessages()
{
// Arrange
Exception exception = new("outer", new InvalidOperationException("inner", new ArgumentException("deepest")));
// Act
string result = exception.AggregateMessages();
// Assert
Assert.Contains("outer", result);
Assert.Contains("inner", result);
Assert.Contains("deepest", result);
Assert.Contains(" -> ", result);
}
[Fact]
public void AggregateMessages_WhenCalledWithSingleException_ShouldReturnItsMessageWithArrow()
{
// Arrange
Exception exception = new("only-message");
// Act
string result = exception.AggregateMessages();
// Assert
Assert.Contains("only-message", result);
Assert.Contains(" -> ", result);
}
[Fact]
public void GetInnerExceptions_WhenExceptionIsNull_ShouldReturnEmptySequence()
{
// Act
IEnumerable<Exception> result = ((Exception)null!).GetInnerExceptions();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetInnerExceptions_WhenExceptionHasNestedInners_ShouldReturnAllLevels()
{
// Arrange
Exception exception = new("first", new InvalidOperationException("second", new ArgumentException("third")));
// Act
List<Exception> result = [.. exception.GetInnerExceptions()];
// Assert
Assert.Equal(3, result.Count);
Assert.Equal("first", result[0].Message);
Assert.Equal("second", result[1].Message);
Assert.Equal("third", result[2].Message);
}
[Fact]
public void GetInnerExceptions_WhenChainExceedsMaximumDepth_ShouldStopAtMaximumDepth()
{
// Arrange
Exception exception = new("level-1", new Exception("level-2", new Exception("level-3", new Exception("level-4", new Exception("level-5", new Exception("level-6"))))));
// Act
List<Exception> result = [.. exception.GetInnerExceptions(maximumDepth: 3)];
// Assert
Assert.Equal(3, result.Count);
Assert.Equal(["level-1", "level-2", "level-3"], result.Select(inner => inner.Message));
}
[Fact]
public void GetInnerExceptions_WhenExceptionIsAggregate_ShouldReturnItsInnerExceptions()
{
// Arrange
AggregateException exception = new(
"aggregate",
[new InvalidOperationException("first-inner", new Exception("first-deep")), new ArgumentException("second-inner")]);
// Act
List<Exception> result = [.. exception.GetInnerExceptions()];
// Assert
// The aggregate exception itself, its inner exceptions and their inners are traversed, and the first inner exception
// is also reachable through the regular InnerException chain, so it is yielded twice.
Assert.Equal(6, result.Count);
Assert.Contains(result, inner => inner is AggregateException);
Assert.Equal(2, result.Count(inner => inner.Message == "first-inner"));
Assert.Equal(2, result.Count(inner => inner.Message == "first-deep"));
Assert.Single(result, inner => inner.Message == "second-inner");
}
[Fact]
public void AggregateMessage_WhenCalled_ShouldContainMessageAndCallStack()
{
// Arrange
Exception exception = new("some-message");
// Act
string result = exception.AggregateMessage();
// Assert
Assert.Contains("Message: some-message", result);
Assert.Contains("CallStack:", result);
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Common.Utilities;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="ImageTypeUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ImageTypeUtilitiesTests
{
[Theory]
[InlineData(ImageType.BMP, "bmp")] // Bitmap image.
[InlineData(ImageType.GIF, "gif")] // Graphics interchange format.
[InlineData(ImageType.PNG, "png")] // Portable network graphics.
[InlineData(ImageType.TIFF, "tiff")] // Tagged image file format.
[InlineData(ImageType.PICT, "pct")] // Macintosh picture.
[InlineData(ImageType.ICO, "ico")] // Icon format.
[InlineData(ImageType.PSD, "psd")] // Photoshop document.
[InlineData(ImageType.JPEG2000, "jp2")] // JPEG 2000.
[InlineData(ImageType.AVIF, "avif")] // AV1 image file format.
[InlineData(ImageType.WEBP, "webp")] // Web picture format.
[InlineData(ImageType.TGA, "tga")] // Truevision TGA.
[InlineData(ImageType.SVG, "svg")] // Scalable vector graphics.
public void ToFileExtension_WhenTypeIsRecognized_ShouldReturnConventionalExtension(ImageType imageType, string expectedExtension)
{
// Act
string result = imageType.ToFileExtension();
// Assert
Assert.Equal(expectedExtension, result);
}
[Theory]
[InlineData(ImageType.JPEG)] // Joint photographic experts group.
[InlineData(ImageType.JPEG_CANON)] // Canon-specific JPEG.
[InlineData(ImageType.JPEG_UNKNOWN)] // Unknown JPEG.
public void ToFileExtension_WhenTypeIsAnyJpeg_ShouldReturnJpg(ImageType imageType)
{
// Act
string result = imageType.ToFileExtension();
// Assert
Assert.Equal("jpg", result);
}
[Fact]
public void ToFileExtension_WhenTypeIsNotARecognizedImage_ShouldReturnBin()
{
// Act
string result = ImageType.None.ToFileExtension();
// Assert
Assert.Equal("bin", result);
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Infrastructure.Common.Utilities;
using Lumina.Infrastructure.Common.Validation;
using Lumina.Infrastructure.Fixtures.Common.Utilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Utilities;
/// <summary>
/// Contains unit tests for the <see cref="OptionsBuilderValidationUtilities"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class OptionsBuilderValidationUtilitiesTests
{
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="OptionsBuilderValidationUtilitiesTests"/> class.
/// </summary>
public OptionsBuilderValidationUtilitiesTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void ValidateFluently_WhenCalled_ShouldRegisterFluentValidationOptions()
{
// Arrange
IServiceCollection services = Substitute.For<IServiceCollection>();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> result = optionsBuilder.ValidateFluently();
// Assert
Assert.Same(optionsBuilder, result);
services.Received(1).Add(Arg.Is<ServiceDescriptor>(sd =>
sd.ServiceType == typeof(IValidateOptions<OptionsBuilderValidationUtilitiesFixture>) &&
sd.Lifetime == ServiceLifetime.Singleton &&
sd.ImplementationFactory != null));
}
[Fact]
public void ValidateFluently_WhenCalled_ShouldUseCorrectName()
{
// Arrange
ServiceCollection services = new();
string name = _fixture.Create<string>();
OptionsBuilder<OptionsBuilderValidationUtilitiesFixture> optionsBuilder = new(services, name);
// Act
optionsBuilder.ValidateFluently();
// Assert
ServiceDescriptor? serviceDescriptor = services.FirstOrDefault(sd =>
sd.ServiceType == typeof(IValidateOptions<OptionsBuilderValidationUtilitiesFixture>) &&
sd.Lifetime == ServiceLifetime.Singleton &&
sd.ImplementationFactory != null);
Assert.NotNull(serviceDescriptor);
Func<IServiceProvider, object>? implementationFactory = serviceDescriptor!.ImplementationFactory;
Assert.NotNull(implementationFactory);
IServiceProvider serviceProvider = Substitute.For<IServiceProvider>();
IValidator<OptionsBuilderValidationUtilitiesFixture> mockValidator = Substitute.For<IValidator<OptionsBuilderValidationUtilitiesFixture>>();
serviceProvider.GetService(typeof(IValidator<OptionsBuilderValidationUtilitiesFixture>))
.Returns(mockValidator);
ValidationOptions<OptionsBuilderValidationUtilitiesFixture>? validationOptions = implementationFactory!(serviceProvider) as ValidationOptions<OptionsBuilderValidationUtilitiesFixture>;
Assert.NotNull(validationOptions);
Assert.Equal(name, validationOptions.Name);
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Validation;
using Lumina.Infrastructure.Fixtures.Common.Validation;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validation;
/// <summary>
/// Contains unit tests for the <see cref="ValidationOptions"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ValidationOptionsTests
{
private readonly IFixture _fixture;
private readonly ValidationOptionsFixture _validationOptionsFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ValidationOptionsTests"/> class.
/// </summary>
public ValidationOptionsTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenMatchingName_ShouldValidateOptions()
{
// Arrange
string name = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.False(result.Failed);
validator.Received(1).Validate(options);
}
[Fact]
public void Validate_WhenNonMatchingName_ShouldSkipValidation()
{
// Arrange
string name = _fixture.Create<string>();
string differentName = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(differentName, options);
// Assert
Assert.Equal(ValidateOptionsResult.Skip, result);
validator.DidNotReceive().Validate(options);
}
[Fact]
public void Validate_WhenNullName_ShouldValidateOptions()
{
// Arrange
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
validator.Validate(options).Returns([]);
ValidationOptions<ValidationOptionsFixture> sut = new(null, validator);
// Act
ValidateOptionsResult result = sut.Validate(_fixture.Create<string>(), options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.False(result.Failed);
validator.Received(1).Validate(options);
}
[Fact]
public void Validate_WhenNullOptions_ShouldThrowArgumentNullException()
{
// Arrange
string name = _fixture.Create<string>();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
Action act = () => sut.Validate(name, null!);
// Assert
Assert.Throws<ArgumentNullException>(() => sut.Validate(name, null!));
}
[Fact]
public void Validate_WhenInvalidOptions_ShouldReturnFailureResult()
{
// Arrange
string name = _fixture.Create<string>();
ValidationOptionsFixture options = _validationOptionsFixture.Create();
IValidator<ValidationOptionsFixture> validator = Substitute.For<IValidator<ValidationOptionsFixture>>();
List<Error> validationFailures =
[
Error.Validation("PropertyName", "Error Message")
];
validator.Validate(options).Returns(validationFailures);
ValidationOptions<ValidationOptionsFixture> sut = new(name, validator);
// Act
ValidateOptionsResult result = sut.Validate(name, options);
// Assert
Assert.IsType<ValidateOptionsResult>(result);
Assert.True(result.Failed);
Assert.Single(result.Failures);
Assert.Contains("Options validation failed for 'PropertyName' with error: 'Error Message'", result.Failures);
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="CorsSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CorsSettingsDtoValidatorTests
{
private readonly CorsSettingsDtoValidator _validator = new();
private readonly CorsSettingsDtoFixture _corsSettingsDtoFixture = new();
[Fact]
public void Validate_WhenOriginsAreValidAbsoluteUrls_ShouldNotHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com", "http://localhost:4200"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenOriginIsWildcard_ShouldNotHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["*"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenAllowedOriginsIsEmpty_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create([]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginsCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasTrailingSlash_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com/"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasNoScheme_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["app.example.com"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginHasUnsupportedScheme_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["ftp://app.example.com"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOneOriginIsInvalid_ShouldHaveValidationErrorForThatOrigin()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://valid.example.com", "invalid-origin"]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description);
}
[Fact]
public void Validate_WhenOriginIsEmptyString_ShouldHaveValidationError()
{
// Arrange
CorsSettingsDto model = _corsSettingsDtoFixture.Create([""]);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Equal(2, result.Count);
Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginsCannotBeEmpty.Description);
Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginIsInvalid.Description);
}
}
@@ -0,0 +1,61 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="DatabaseSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DatabaseSettingsDtoValidatorTests
{
private readonly DatabaseSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseSettingsDtoValidatorTests"/> class.
/// </summary>
public DatabaseSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenDefaultConnectionProvided_ShouldNotHaveValidationError()
{
// Arrange
DatabaseSettingsDto model = _fixture.Build<DatabaseSettingsDto>()
.With(x => x.DefaultConnection, "dummy-connection-string")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenDefaultConnectionNotProvided_ShouldHaveValidationError()
{
// Arrange
DatabaseSettingsDto model = _fixture.Build<DatabaseSettingsDto>()
.With(x => x.DefaultConnection, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,80 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="EncryptionSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EncryptionSettingsDtoValidatorTests
{
private readonly EncryptionSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsDtoValidatorTests"/> class.
/// </summary>
public EncryptionSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenValidBase64SecretKeyProvided_ShouldNotHaveValidationError()
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, "dGhpcyBpcyBhIHZhbGlkIGJhc2U2NCBzdHJpbmc=") // "this is a valid base64 string" in base64.
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description, result[0].Description);
}
[Theory]
[InlineData("not-a-base64-string")]
[InlineData("invalid!base64")]
[InlineData("123")]
public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError(string invalidBase64)
{
// Arrange
EncryptionSettingsDto model = _fixture.Build<EncryptionSettingsDto>()
.With(x => x.SecretKey, invalidBase64)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description, result[0].Description);
}
}
@@ -0,0 +1,147 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="JwtSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtSettingsDtoValidatorTests
{
private readonly JwtSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="JwtSettingsDtoValidatorTests"/> class.
/// </summary>
public JwtSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationErrors()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, string.Empty)
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Equal(2, result.Count);
Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description);
Assert.Contains(result, error => error.Description == Errors.Configuration.JwtSecretKeyTooShort.Description);
}
[Fact]
public void Validate_WhenSecretKeyTooShort_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "short-key")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtSecretKeyTooShort.Description, result[0].Description);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
[InlineData(-60)]
public void Validate_WhenExpiryMinutesNotPositive_ShouldHaveValidationError(int minutes)
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, minutes)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtExpiryMinutesMustBePositive.Description, result[0].Description);
}
[Fact]
public void Validate_WhenIssuerIsEmpty_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, string.Empty)
.With(x => x.Audience, "test-audience")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtIssuerCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenAudienceIsEmpty_ShouldHaveValidationError()
{
// Arrange
JwtSettingsDto model = _fixture.Build<JwtSettingsDto>()
.With(x => x.SecretKey, "this-is-a-very-long-secret-key-for-testing")
.With(x => x.ExpiryMinutes, 30)
.With(x => x.Issuer, "test-issuer")
.With(x => x.Audience, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.JwtAudienceCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,124 @@
#region ========================================================================= USING =====================================================================================
using AutoFixture;
using AutoFixture.AutoNSubstitute;
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Validators;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="MediaSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaSettingsDtoValidatorTests
{
private readonly MediaSettingsDtoValidator _validator = new();
private readonly IFixture _fixture;
/// <summary>
/// Initializes a new instance of the <see cref="MediaSettingsDtoValidatorTests"/> class.
/// </summary>
public MediaSettingsDtoValidatorTests()
{
_fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
}
[Fact]
public void Validate_WhenRootDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, "/path/to/media")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenRootDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenRootDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.RootDirectory, " ")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, string.Empty)
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, "/path/to/media")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenMediaLibrariesDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
MediaSettingsDto model = _fixture.Build<MediaSettingsDto>()
.With(x => x.LibrariesDirectory, " ")
.Create();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,62 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="PluginsSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginsSettingsDtoValidatorTests
{
private readonly PluginsSettingsDtoValidator _validator = new();
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
[Fact]
public void Validate_WhenDirectoryProvided_ShouldNotHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: "/path/to/plugins");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenDirectoryIsEmpty_ShouldHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: string.Empty);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenDirectoryIsWhitespace_ShouldHaveValidationError()
{
// Arrange
PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: " ");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description);
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="ThemeEngineOptionsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeEngineOptionsDtoValidatorTests
{
private readonly ThemeEngineOptionsDtoValidator _validator = new();
private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new();
[Fact]
public void Validate_WhenAllPropertiesValid_ShouldNotHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create();
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Empty(result);
}
[Fact]
public void Validate_WhenStoragePathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(storagePath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeStoragePathCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenBundledThemesPathIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(bundledThemesPath: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeBundledThemesPathCannotBeEmpty.Description, result[0].Description);
}
[Fact]
public void Validate_WhenDefaultThemeIdIsEmpty_ShouldHaveValidationError()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(defaultThemeId: string.Empty);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeDefaultThemeIdCannotBeEmpty.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxArchiveBytesIsNotPositive_ShouldHaveValidationError(long maxArchiveBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxArchiveBytes: maxArchiveBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxArchiveBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxExpandedBytesIsNotPositive_ShouldHaveValidationError(long maxExpandedBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxExpandedBytes: maxExpandedBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxExpandedBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0L)] // Zero, not positive.
[InlineData(-1L)] // Negative.
public void Validate_WhenMaxSingleFileBytesIsNotPositive_ShouldHaveValidationError(long maxSingleFileBytes)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxSingleFileBytes: maxSingleFileBytes);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxSingleFileBytesMustBePositive.Description, result[0].Description);
}
[Theory]
[InlineData(0)] // Zero, not positive.
[InlineData(-1)] // Negative.
public void Validate_WhenMaxEntriesIsNotPositive_ShouldHaveValidationError(int maxEntries)
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(maxEntries: maxEntries);
// Act
List<Error> result = _validator.Validate(options);
// Assert
Assert.Single(result);
Assert.Equal(Errors.Configuration.ThemeMaxEntriesMustBePositive.Description, result[0].Description);
}
}
@@ -0,0 +1,454 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Infrastructure.Common.Errors;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Common.Validators;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Abstractions;
#endregion
namespace Lumina.Infrastructure.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="TranscodingSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingSettingsDtoValidatorTests : IDisposable
{
private readonly TranscodingSettingsDtoValidator _validator;
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
private readonly string _sandboxRoot;
private readonly string _mediaRoot;
private readonly string _validCacheDirectory;
private readonly string _pluginsDirectory;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingSettingsDtoValidatorTests"/> class.
/// </summary>
public TranscodingSettingsDtoValidatorTests()
{
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-transcoding-validator-tests-" + Guid.NewGuid().ToString("N"));
_mediaRoot = Path.Combine(_sandboxRoot, "media");
_validCacheDirectory = Path.Combine(_sandboxRoot, "cache");
_pluginsDirectory = Path.Combine(_sandboxRoot, "plugins");
Directory.CreateDirectory(_mediaRoot);
Directory.CreateDirectory(_validCacheDirectory);
Directory.CreateDirectory(_pluginsDirectory);
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
? new WindowsPathStrategy(new FileSystem())
: new UnixPathStrategy(new FileSystem());
platformContext.PathStrategy.Returns(pathStrategy);
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
platformContextManager.GetCurrentContext().Returns(platformContext);
IPathService pathService = new PathService(platformContextManager);
// An absolute root directory pins the media root that is served by the media route, because Path.Combine returns its second argument when it is rooted.
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: _mediaRoot);
PluginsSettingsDto pluginsSettings = _pluginsSettingsDtoFixture.Create(directory: _pluginsDirectory);
_validator = new TranscodingSettingsDtoValidator(Options.Create(mediaSettings), Options.Create(pluginsSettings), pathService);
}
[Fact]
public void Validate_WhenSettingsAreValid_ShouldNotHaveAnyValidationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings();
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // A missing ffmpeg path.
[InlineData("")] // An empty ffmpeg path.
[InlineData(" ")] // A whitespace ffmpeg path.
public void Validate_WhenFfmpegPathIsEmpty_ShouldHaveFfmpegPathCannotBeEmptyError(string? ffmpegPath)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(ffmpegPath: ffmpegPath, includeFfmpegPath: ffmpegPath is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty.Description);
}
[Theory]
[InlineData(0)] // A job count of zero disables normalization.
[InlineData(-1)] // A negative job count disables normalization.
public void Validate_WhenMaxConcurrentJobsIsNotPositive_ShouldHaveMaxConcurrentJobsMustBePositiveError(int maxConcurrentJobs)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: maxConcurrentJobs, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTooLarge_ShouldHaveMaxConcurrentJobsIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 65, maxConcurrentJobsPerUser: 1);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsIsTheMaximum_ShouldNotHaveMaxConcurrentJobsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 64);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive.Description);
}
[Theory]
[InlineData(0)] // A per-user job count of zero never admits a normalization.
[InlineData(-1)] // A negative per-user job count never admits a normalization.
public void Validate_WhenMaxConcurrentJobsPerUserIsNotPositive_ShouldHaveMaxConcurrentJobsPerUserMustBePositiveError(int maxConcurrentJobsPerUser)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: maxConcurrentJobsPerUser);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserMustBePositive.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserIsTooLarge_ShouldHaveMaxConcurrentJobsPerUserIsTooLargeError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 64, maxConcurrentJobsPerUser: 65);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Fact]
public void Validate_WhenMaxConcurrentJobsPerUserExceedsTheGlobalLimit_ShouldHaveMaxConcurrentJobsPerUserExceedsGlobalError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxConcurrentJobs: 8, maxConcurrentJobsPerUser: 16);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserExceedsGlobal.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingMaxConcurrentJobsPerUserIsTooLarge.Description);
}
[Theory]
[InlineData(0)] // A cache with no capacity cannot hold a normalized track.
[InlineData(-1)] // A negative cache size is not a capacity.
public void Validate_WhenMaxCacheBytesIsNotPositive_ShouldHaveMaxCacheBytesMustBePositiveError(long maxCacheBytes)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(maxCacheBytes: maxCacheBytes);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingMaxCacheBytesMustBePositive.Description);
}
[Theory]
[InlineData(0)] // A job timeout of zero stops every job immediately.
[InlineData(-1)] // A negative job timeout stops every job immediately.
public void Validate_WhenJobTimeoutSecondsIsNotPositive_ShouldHaveJobTimeoutMustBePositiveError(int jobTimeoutSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: jobTimeoutSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTooLong_ShouldHaveJobTimeoutIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
}
[Fact]
public void Validate_WhenJobTimeoutSecondsIsTheMaximum_ShouldNotHaveJobTimeoutErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(jobTimeoutSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingJobTimeoutMustBePositive.Description);
}
[Theory]
[InlineData(0)] // An eviction grace of zero protects nothing.
[InlineData(-1)] // A negative eviction grace protects nothing.
public void Validate_WhenEvictionGraceSecondsIsNotPositive_ShouldHaveEvictionGraceSecondsMustBePositiveError(int evictionGraceSeconds)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: evictionGraceSeconds);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTooLong_ShouldHaveEvictionGraceSecondsIsTooLongError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_401);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
}
[Fact]
public void Validate_WhenEvictionGraceSecondsIsTheMaximum_ShouldNotHaveEvictionGraceSecondsErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(evictionGraceSeconds: 86_400);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsMalformed_ShouldHaveCacheDirectoryIsInvalidError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: "bad\0path");
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInvalid.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsInsideTheMediaRoot_ShouldHaveCacheDirectoryIsInsideMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(_mediaRoot, "cache"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryContainsTheMediaRoot_ShouldHaveCacheDirectoryContainsMediaRootError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _sandboxRoot);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot.Description);
Assert.DoesNotContain(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAFileSystemRoot_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.GetPathRoot(_mediaRoot)!);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheApplicationBaseDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: AppContext.BaseDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsTheLogsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: Path.Combine(AppContext.BaseDirectory, "logs"));
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsThePluginsDirectory_ShouldHaveCacheDirectoryIsUnsafeLocationError()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _pluginsDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Contains(result, error => error.Description == Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation.Description);
}
[Fact]
public void Validate_WhenCacheDirectoryIsAValidExternalDirectory_ShouldNotHaveCacheDirectoryErrors()
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: _validCacheDirectory);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
[Theory]
[InlineData(null)] // No configured directory, so the default temporary directory is used.
[InlineData(" ")] // A whitespace directory, so the default temporary directory is used.
public void Validate_WhenCacheDirectoryIsNotConfigured_ShouldOnlyValidateTheDefaultDirectory(string? cacheDirectory)
{
// Arrange
TranscodingSettingsDto model = CreateSettings(cacheDirectory: cacheDirectory, includeCacheDirectory: cacheDirectory is not null);
// Act
List<Error> result = _validator.Validate(model);
// Assert
Assert.Empty(result);
}
/// <summary>
/// Releases the temporary directories the containment tests use.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
/// <summary>
/// Creates settings that are valid unless an argument overrides a single rule under test.
/// </summary>
/// <param name="ffmpegPath">The file name or path of the ffmpeg binary.</param>
/// <param name="maxConcurrentJobs">The maximum number of normalization jobs that may run at the same time.</param>
/// <param name="maxConcurrentJobsPerUser">The maximum number of normalization jobs a single user may have running at the same time.</param>
/// <param name="maxCacheBytes">The maximum total size of the normalized audio cache, in bytes.</param>
/// <param name="jobTimeoutSeconds">The maximum duration of a single normalization job, in seconds.</param>
/// <param name="evictionGraceSeconds">The period during which a cache entry is protected from eviction, in seconds.</param>
/// <param name="cacheDirectory">The directory where normalized audio is cached.</param>
/// <param name="includeCacheDirectory">Whether the cache directory should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeFfmpegPath">Whether the ffmpeg path should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created settings.</returns>
private TranscodingSettingsDto CreateSettings(
string? ffmpegPath = "ffmpeg",
int? maxConcurrentJobs = 8,
int? maxConcurrentJobsPerUser = 4,
long? maxCacheBytes = 2L * 1024 * 1024 * 1024,
int? jobTimeoutSeconds = 900,
int? evictionGraceSeconds = 120,
string? cacheDirectory = null,
bool includeCacheDirectory = true,
bool includeFfmpegPath = true)
{
return _transcodingSettingsDtoFixture.Create(
ffmpegPath: ffmpegPath,
maxConcurrentJobs: maxConcurrentJobs,
maxConcurrentJobsPerUser: maxConcurrentJobsPerUser,
maxCacheBytes: maxCacheBytes,
jobTimeoutSeconds: jobTimeoutSeconds,
evictionGraceSeconds: evictionGraceSeconds,
cacheDirectory: cacheDirectory ?? _validCacheDirectory,
includeCacheDirectory: includeCacheDirectory,
includeFfmpegPath: includeFfmpegPath);
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Fixtures.Core.Authentication;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="JwtTokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtTokenGeneratorTests
{
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly JwtSettingsDto _jwtSettings;
private readonly JwtTokenGenerator _sut;
private readonly DateTime _fixedUtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="JwtTokenGeneratorTests"/> class.
/// </summary>
public JwtTokenGeneratorTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_jwtSettings = JwtTokenGeneratorFixture.CreateJwtSettings();
_fixedUtcNow = new DateTime(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc);
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
IOptions<JwtSettingsDto> options = Substitute.For<IOptions<JwtSettingsDto>>();
options.Value.Returns(_jwtSettings);
_sut = new JwtTokenGenerator(_mockDateTimeProvider, options);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldCreateValidJwtToken()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
JwtSecurityTokenHandler tokenHandler = new();
// Act
string token = _sut.GenerateToken(userId, username);
// Assert
Assert.NotNull(token);
Assert.NotEmpty(token);
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
// Verify token properties.
Assert.Equal(_jwtSettings.Issuer, jwtToken.Issuer);
Assert.Single(jwtToken.Audiences, _jwtSettings.Audience);
Assert.Equal(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes), jwtToken.ValidTo);
// Verify claims.
Assert.Contains(jwtToken.Claims, c => c.Type == JwtRegisteredClaimNames.Sub && c.Value == userId);
Assert.Contains(jwtToken.Claims, c => c.Type == JwtRegisteredClaimNames.UniqueName && c.Value == username);
Assert.Contains(jwtToken.Claims, c => c.Type == JwtRegisteredClaimNames.Jti && c.Value == userId);
// Verify the token is actually valid.
TokenValidationParameters validationParameters = new()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey)),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
// Override the current time to match our fixed test time.
LifetimeValidator = (notBefore, expires, token, parameters) => expires > _fixedUtcNow
};
ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
Assert.NotNull(principal);
Assert.NotNull(validatedToken);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldUseProvidedDateTimeForExpiration()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
JwtSecurityTokenHandler tokenHandler = new();
// Act
string token = _sut.GenerateToken(userId, username);
JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);
// Assert
Assert.Equal(_fixedUtcNow.AddMinutes(_jwtSettings.ExpiryMinutes), jwtToken.ValidTo);
_ = _mockDateTimeProvider.Received(1).UtcNow;
}
[Fact]
public void GenerateToken_WhenCalledWithDifferentUsers_ShouldCreateUniqueTokens()
{
// Arrange
(string userId1, string username1) = JwtTokenGeneratorFixture.CreateUserCredentials();
(string userId2, string username2) = JwtTokenGeneratorFixture.CreateUserCredentials();
// Act
string token1 = _sut.GenerateToken(userId1, username1);
string token2 = _sut.GenerateToken(userId2, username2);
// Assert
Assert.NotEqual(token1, token2);
}
[Fact]
public void GenerateToken_WhenCalledMultipleTimesForSameUser_ShouldCreateIdenticalTokens()
{
// Arrange
(string userId, string username) = JwtTokenGeneratorFixture.CreateUserCredentials();
// Act
string token1 = _sut.GenerateToken(userId, username);
string token2 = _sut.GenerateToken(userId, username);
// Assert
Assert.Equal(token1, token2);
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Authentication;
using Lumina.Infrastructure.Fixtures.Core.Authentication;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="QRCodeGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class QRCodeGeneratorTests
{
private readonly QRCodeGenerator _sut = new();
[Fact]
public void GenerateQrCodeDataUri_WhenCalled_ShouldReturnValidDataUri()
{
// Arrange
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
Assert.StartsWith("data:image/png;base64,", result);
Assert.True(IsBase64String(result[22..])); // Skip "data:image/png;base64,".
}
[Fact]
public void GenerateQrCodeDataUri_WhenUsernameContainsSpecialCharacters_ShouldEscapeUsername()
{
// Arrange
string username = "user@example.com";
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
Assert.StartsWith("data:image/png;base64,", result);
Assert.True(IsBase64String(result[22..]));
}
[Fact]
public void GenerateQrCodeDataUri_WhenCalled_ShouldGenerateUniqueQrCodesForDifferentUsers()
{
// Arrange
(string username1, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
string username2 = username1 + "_different";
// Act
string result1 = _sut.GenerateQrCodeDataUri(username1, secret);
string result2 = _sut.GenerateQrCodeDataUri(username2, secret);
// Assert
Assert.NotEqual(result1, result2);
}
[Fact]
public void GenerateQrCodeDataUri_WhenCalledWithSameInput_ShouldGenerateIdenticalQrCodes()
{
// Arrange
(string username, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result1 = _sut.GenerateQrCodeDataUri(username, secret);
string result2 = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
Assert.Equal(result1, result2);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public void GenerateQrCodeDataUri_WhenUsernameIsInvalid_ShouldStillGenerateQrCode(string? invalidUsername)
{
// Arrange
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(invalidUsername!, secret);
// Assert
Assert.StartsWith("data:image/png;base64,", result);
Assert.True(IsBase64String(result[22..]));
}
[Theory]
[InlineData("user@example.com")]
[InlineData("user name with spaces")]
[InlineData("user+with+plus")]
[InlineData("user/with/slashes")]
public void GenerateQrCodeDataUri_WhenUsernameHasSpecialCharacters_ShouldStillGenerateQrCode(string username)
{
// Arrange
(_, byte[] secret) = QRCodeGeneratorFixture.CreateQrCodeTestData();
// Act
string result = _sut.GenerateQrCodeDataUri(username, secret);
// Assert
Assert.StartsWith("data:image/png;base64,", result);
Assert.True(IsBase64String(result[22..]));
}
[Fact]
public void GenerateQrCodeDataUri_WhenSecretIsTooShort_ShouldStillGenerateQrCode()
{
// Arrange
(string username, _) = QRCodeGeneratorFixture.CreateQrCodeTestData();
byte[] shortSecret = [1]; // Minimum length for Base32 encoding.
// Act
string result = _sut.GenerateQrCodeDataUri(username, shortSecret);
// Assert
Assert.StartsWith("data:image/png;base64,", result);
Assert.True(IsBase64String(result[22..]));
}
private static bool IsBase64String(string base64)
{
try
{
Convert.FromBase64String(base64);
return true;
}
catch
{
return false;
}
}
}
@@ -0,0 +1,63 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Authentication;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="TokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TokenGeneratorTests
{
private readonly TokenGenerator _sut = new();
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateNonEmptyToken()
{
// Act
string token = _sut.GenerateToken();
// Assert
Assert.NotNull(token);
Assert.NotEmpty(token);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateUrlSafeToken()
{
// Act
string token = _sut.GenerateToken();
// Assert
Assert.DoesNotContain("+", token);
Assert.DoesNotContain("/", token);
Assert.DoesNotContain("=", token);
}
[Fact]
public void GenerateToken_WhenCalledMultipleTimes_ShouldGenerateUniqueTokens()
{
// Act
string token1 = _sut.GenerateToken();
string token2 = _sut.GenerateToken();
string token3 = _sut.GenerateToken();
// Assert
Assert.NotEqual(token1, token2);
Assert.NotEqual(token1, token3);
Assert.NotEqual(token2, token3);
}
[Fact]
public void GenerateToken_WhenCalled_ShouldGenerateTokenOfCorrectLength()
{
// Act
string token = _sut.GenerateToken();
// Assert
// 32 bytes in Base64 without padding should be 43 characters.
Assert.Equal(43, token.Length);
}
}
@@ -0,0 +1,100 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Authentication;
using OtpNet;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authentication;
/// <summary>
/// Contains unit tests for the <see cref="TotpTokenGenerator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TotpTokenGeneratorTests
{
private readonly TotpTokenGenerator _sut = new();
[Fact]
public void GenerateSecret_WhenCalled_ShouldGenerateNonEmptySecret()
{
// Act
byte[] secret = _sut.GenerateSecret();
// Assert
Assert.NotEmpty(secret);
}
[Fact]
public void GenerateSecret_WhenCalledMultipleTimes_ShouldGenerateUniqueSecrets()
{
// Act
byte[] secret1 = _sut.GenerateSecret();
byte[] secret2 = _sut.GenerateSecret();
byte[] secret3 = _sut.GenerateSecret();
// Assert
Assert.NotEqual(secret1, secret2);
Assert.NotEqual(secret1, secret3);
Assert.NotEqual(secret2, secret3);
}
[Fact]
public void ValidateToken_WhenTokenIsValid_ShouldReturnTrue()
{
// Arrange
byte[] secret = _sut.GenerateSecret();
Totp totp = new(secret);
string validToken = totp.ComputeTotp();
// Act
bool result = _sut.ValidateToken(secret, validToken);
// Assert
Assert.True(result);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("123456")] // Valid format but wrong token.
[InlineData("abcdef")] // Invalid format.
[InlineData("12345")] // Too short.
[InlineData("1234567")] // Too long.
public void ValidateToken_WhenTokenIsInvalid_ShouldReturnFalse(string invalidToken)
{
// Arrange
byte[] secret = _sut.GenerateSecret();
// Act
bool result = _sut.ValidateToken(secret, invalidToken);
// Assert
Assert.False(result);
}
[Fact]
public void ValidateToken_WhenSecretIsWrong_ShouldReturnFalse()
{
// Arrange
byte[] secret1 = _sut.GenerateSecret();
byte[] secret2 = _sut.GenerateSecret();
Totp totp = new(secret1);
string token = totp.ComputeTotp();
// Act
bool result = _sut.ValidateToken(secret2, token);
// Assert
Assert.False(result);
}
[Fact]
public void GenerateSecret_WhenCalled_ShouldGenerateSecretOfCorrectLength()
{
// Act
byte[] secret = _sut.GenerateSecret();
// Assert
Assert.Equal(20, secret.Length); // Standard TOTP secret length.
}
}
@@ -0,0 +1,555 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.Fixtures.Core.Authorization;
using NSubstitute;
using NSubstitute.ExceptionExtensions;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization;
/// <summary>
/// Contains unit tests for the <see cref="AuthorizationService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationServiceTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly IAuthorizationPolicyFactory _mockAuthorizationPolicyFactory;
private readonly AuthorizationService _sut;
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizationServiceTests"/> class.
/// </summary>
public AuthorizationServiceTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUserRepository = Substitute.For<IUserRepository>();
_mockAuthorizationPolicyFactory = Substitute.For<IAuthorizationPolicyFactory>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new AuthorizationService(_mockUnitOfWork, _mockAuthorizationPolicyFactory);
}
[Fact]
public async Task HasPermissionAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
bool result = await _sut.HasPermissionAsync(userId, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenGetUserFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
bool result = await _sut.HasPermissionAsync(userId, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasDirectPermission_ShouldReturnTrue()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanViewUsers]);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.True(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasPermissionThroughRole_ShouldReturnTrue()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ "Admin", new[] { AuthorizationPermission.CanViewUsers } }
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.True(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasNoPermissions_ShouldReturnFalse()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasDifferentPermission_ShouldReturnFalse()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanDeleteUsers]);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task HasPermissionAsync_WhenUserHasPermissionBothDirectlyAndThroughRole_ShouldReturnTrue()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ "Admin", new[] { AuthorizationPermission.CanViewUsers } }
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanViewUsers],
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.HasPermissionAsync(user.Id, AuthorizationPermission.CanViewUsers, CancellationToken.None);
// Assert
Assert.True(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
bool result = await _sut.IsInRoleAsync(userId, "Admin", CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenGetUserFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
bool result = await _sut.IsInRoleAsync(userId, "Admin", CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasRole_ShouldReturnTrue()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ "Admin", Array.Empty<AuthorizationPermission>() }
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None);
// Assert
Assert.True(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasDifferentRole_ShouldReturnFalse()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{ "", Array.Empty<AuthorizationPermission>() }
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task IsInRoleAsync_WhenUserHasNoRoles_ShouldReturnFalse()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.IsInRoleAsync(user.Id, "Admin", CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyEvaluationSucceeds_ShouldReturnTrue()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
// Assert
Assert.True(result);
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyEvaluationFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
.Returns(false);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenPolicyThrowsException_ShouldPropagateException()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
.Throws(new InvalidOperationException("Policy evaluation failed"));
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
// Assert
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
Assert.Equal("Policy evaluation failed", exception.Message);
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenFactoryThrowsException_ShouldPropagateException()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Throws(new InvalidOperationException("Policy creation failed"));
// Act
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
// Assert
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
Assert.Equal("Policy creation failed", exception.Message);
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WhenCancellationRequested_ShouldPropagateToken()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
CancellationToken cancellationToken = new(true);
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, cancellationToken);
// Assert
await mockPolicy.Received(1).EvaluateAsync(userId, context, cancellationToken);
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
}
[Fact]
public async Task EvaluatePolicyAsync_WithConcretePolicy_ShouldCreateCorrectPolicyType()
{
// Arrange
Guid userId = Guid.NewGuid();
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
IAuthorizationPolicy mockPolicy = Substitute.For<ITestAuthorizationPolicy>();
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
.Returns(true);
_mockAuthorizationPolicyFactory.CreatePolicy<ITestAuthorizationPolicy>()
.Returns(mockPolicy);
// Act
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, context, CancellationToken.None);
// Assert
Assert.True(result);
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<ITestAuthorizationPolicy>();
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserDoesNotExist_ShouldReturnError()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Users.UserDoesNotExist, result.FirstError);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenGetUserFails_ShouldReturnError()
{
// Arrange
Guid userId = Guid.NewGuid();
Error error = Error.Failure("Database.Error", "Failed to retrieve user");
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(userId, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasNoRolesOrPermissions_ShouldReturnEmptySets()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions();
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.UserId);
Assert.Null(result.Value.Role);
Assert.Empty(result.Value.Permissions);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasOnlyDirectPermissions_ShouldReturnCorrectPermissions()
{
// Arrange
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
directPermissions:
[
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers
]);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.UserId);
Assert.Null(result.Value.Role);
Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers],
result.Value.Permissions);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasOnlyRolePermissions_ShouldReturnCorrectRolesAndPermissions()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{
"Admin",
new[] { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers }
}
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.UserId);
Assert.Equal("Admin", result.Value.Role);
Assert.Equal([AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers],
result.Value.Permissions);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetUserAuthorizationAsync_WhenUserHasBothDirectAndRolePermissions_ShouldReturnCombinedPermissions()
{
// Arrange
Dictionary<string, IEnumerable<AuthorizationPermission>> rolePermissions = new()
{
{
"Admin",
new[] { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers }
}
};
UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(
directPermissions: [AuthorizationPermission.CanRegisterUsers],
rolePermissions: rolePermissions);
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
Result<UserAuthorizationEntity> result = await _sut.GetUserAuthorizationAsync(user.Id, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(user.Id, result.Value.UserId);
Assert.Equal("Admin", result.Value.Role);
Assert.Equivalent(
new HashSet<AuthorizationPermission>
{
AuthorizationPermission.CanViewUsers,
AuthorizationPermission.CanDeleteUsers,
AuthorizationPermission.CanRegisterUsers
},
result.Value.Permissions
);
await _mockUserRepository.Received(1).GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,67 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
using Lumina.Infrastructure.Fixtures.Core.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Common.Factory;
/// <summary>
/// Contains unit tests for the <see cref="AuthorizationPolicyFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthorizationPolicyFactoryTests
{
[Fact]
public void CreatePolicy_WhenCalled_ShouldReturnCorrectPolicy()
{
// Arrange
ServiceCollection services = new();
services.AddTransient<IAuthorizationPolicy, TestAuthorizationPolicy>();
services.AddTransient<TestAuthorizationPolicy>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
AuthorizationPolicyFactory policyFactory = new(serviceProvider);
// Act
TestAuthorizationPolicy result = policyFactory.CreatePolicy<TestAuthorizationPolicy>();
// Assert
Assert.NotNull(result);
Assert.IsAssignableFrom<IAuthorizationPolicy>(result);
Assert.IsType<TestAuthorizationPolicy>(result);
}
[Fact]
public void CreatePolicy_WhenUnregisteredPolicyRequested_ShouldThrowException()
{
// Arrange
ServiceCollection services = new();
ServiceProvider serviceProvider = services.BuildServiceProvider();
AuthorizationPolicyFactory policyFactory = new(serviceProvider);
// Act & Assert
Action act = () => policyFactory.CreatePolicy<IUnregisteredPolicy>();
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
policyFactory.CreatePolicy<IUnregisteredPolicy>());
Assert.Equal("No service for type 'Lumina.Infrastructure.Fixtures.Core.Authorization.IUnregisteredPolicy' has been registered.",
exception.Message);
}
[Fact]
public void CreatePolicy_WhenServiceProviderReturnsNull_ShouldThrowInvalidOperationException()
{
// Arrange
IServiceProvider mockServiceProvider = Substitute.For<IServiceProvider>();
mockServiceProvider.GetService(typeof(TestAuthorizationPolicy))
.Returns(null);
AuthorizationPolicyFactory policyFactory = new(mockServiceProvider);
// Act & Assert
Assert.Throws<InvalidOperationException>(() => policyFactory.CreatePolicy<TestAuthorizationPolicy>());
}
}
@@ -0,0 +1,189 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Fixtures.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Fixtures.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.ConsumptionActivity;
/// <summary>
/// Contains unit tests for the <see cref="ConsumptionActivityAccessPolicy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ConsumptionActivityAccessPolicyTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ConsumptionActivityAccessPolicy _sut;
private readonly ConsumptionActivityAccessPolicyContextFixture _consumptionActivityAccessPolicyContextFixture = new();
private readonly LibraryOwnershipPolicyContextFixture _libraryOwnershipPolicyContextFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ConsumptionActivityAccessPolicyTests"/> class.
/// </summary>
public ConsumptionActivityAccessPolicyTests()
{
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
_sut = new ConsumptionActivityAccessPolicy(_mockAuthorizationService);
}
[Fact]
public async Task EvaluateAsync_WhenUserIdIsEmpty_ShouldReturnFalseWithoutCheckingRole()
{
// Arrange
Guid userId = Guid.Empty;
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
// A user in the admin role would make the policy return true, so a false result can only come from the empty user Id guard.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.False(result);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenContextIsNull_ShouldReturnFalseWithoutCheckingRole()
{
// Arrange
Guid userId = Guid.NewGuid();
CancellationToken cancellationToken = CancellationToken.None;
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
bool result = await _sut.EvaluateAsync(userId, null, cancellationToken);
// Assert
Assert.False(result);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenContextIsNotConsumptionActivityContext_ShouldReturnFalseWithoutCheckingRole()
{
// Arrange
Guid userId = Guid.NewGuid();
LibraryOwnershipPolicyContext context = _libraryOwnershipPolicyContextFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.False(result);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenTargetUserIdIsEmpty_ShouldReturnFalseWithoutCheckingRole()
{
// Arrange
Guid userId = Guid.NewGuid();
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create(targetUserId: Guid.Empty);
CancellationToken cancellationToken = CancellationToken.None;
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.False(result);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenTargetUserIsTheSameUser_ShouldReturnTrueWithoutCheckingRole()
{
// Arrange
Guid userId = Guid.NewGuid();
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create(targetUserId: userId);
CancellationToken cancellationToken = CancellationToken.None;
// The user is deliberately not an admin, so an implementation that still consulted the roles would return false.
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.True(result);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenTargetUserIsDifferentAndUserIsInAdminRole_ShouldReturnTrue()
{
// Arrange
Guid userId = Guid.NewGuid();
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create(targetUserId: Guid.NewGuid());
CancellationToken cancellationToken = CancellationToken.None;
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(true);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.True(result);
await _mockAuthorizationService.Received(1).IsInRoleAsync(
Arg.Is(userId),
Arg.Is(AuthorizationRoles.ADMIN),
Arg.Is(cancellationToken));
}
[Fact]
public async Task EvaluateAsync_WhenTargetUserIsDifferentAndUserIsNotInAdminRole_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create(targetUserId: Guid.NewGuid());
CancellationToken cancellationToken = CancellationToken.None;
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(false);
// Act
bool result = await _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
Assert.False(result);
await _mockAuthorizationService.Received(1).IsInRoleAsync(
Arg.Is(userId),
Arg.Is(AuthorizationRoles.ADMIN),
Arg.Is(cancellationToken));
}
[Fact]
public async Task EvaluateAsync_WhenRoleCheckIsCancelled_ShouldPropagateCancellation()
{
// Arrange
Guid userId = Guid.NewGuid();
ConsumptionActivityAccessPolicyContext context = _consumptionActivityAccessPolicyContextFixture.Create(targetUserId: Guid.NewGuid());
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
_mockAuthorizationService.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<bool>(new OperationCanceledException(cancellationToken)));
// Act
Task<bool> operation = _sut.EvaluateAsync(userId, context, cancellationToken);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
}
}
@@ -0,0 +1,172 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
using Lumina.Infrastructure.Fixtures.Core.Authorization;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.LibraryOwnership;
/// <summary>
/// Contains unit tests for the <see cref="LibraryOwnershipPolicy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryOwnershipPolicyTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly LibraryOwnershipPolicy _sut;
private readonly AuthorizationServiceFixture _authorizationServiceFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryOwnershipPolicyTests"/> class.
/// </summary>
public LibraryOwnershipPolicyTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new LibraryOwnershipPolicy(_mockUnitOfWork);
}
[Fact]
public async Task EvaluateAsync_WhenContextIsNotLibraryOwnershipContext_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
// Act
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
// Assert
Assert.False(result);
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>());
}
[Fact]
public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenGetUserFails_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve user"));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenUserIsAdmin_ShouldReturnTrue()
{
// Arrange
UserEntity adminUser = _authorizationServiceFixture.CreateUserWithPermissions(
rolePermissions: new Dictionary<string, IEnumerable<AuthorizationPermission>>
{
{ "Admin", [] }
});
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
_mockUserRepository.GetByIdAsync(adminUser.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(adminUser));
// Act
bool result = await _sut.EvaluateAsync(adminUser.Id, context, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task EvaluateAsync_WhenUserOwnsLibrary_ShouldReturnTrue()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryEntity library = _libraryEntityFixture.Create(userId: userId);
regularUser.Libraries.Add(library);
LibraryOwnershipPolicyContext context = new(library.Id);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task EvaluateAsync_WhenUserDoesNotOwnLibrary_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryEntity library = _libraryEntityFixture.Create(userId: Guid.NewGuid());
LibraryOwnershipPolicyContext context = new(library.Id);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
// Act
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenMultipleLibrariesAreEvaluated_ShouldReadTheUserOnlyOnce()
{
// Arrange
Guid userId = Guid.NewGuid();
UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions();
LibraryEntity ownedLibrary = _libraryEntityFixture.Create(userId: userId);
regularUser.Libraries.Add(ownedLibrary);
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(regularUser));
// Act
// The policy is scoped to one request, so both library checks in that scope must share a single user read.
bool canAccessOwnedLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(ownedLibrary.Id), CancellationToken.None);
bool canAccessOtherLibrary = await _sut.EvaluateAsync(userId, new LibraryOwnershipPolicyContext(Guid.NewGuid()), CancellationToken.None);
// Assert
Assert.True(canAccessOwnedLibrary);
Assert.False(canAccessOtherLibrary);
await _mockUserRepository.Received(1).GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,101 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Over18;
/// <summary>
/// Contains unit tests for the <see cref="Over18Policy"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class Over18PolicyTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IUserRepository _mockUserRepository;
private readonly Over18Policy _sut;
private readonly UserEntityFixture _userEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="Over18PolicyTests"/> class.
/// </summary>
public Over18PolicyTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockUserRepository = Substitute.For<IUserRepository>();
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
_sut = new Over18Policy(_mockUnitOfWork, Substitute.For<IDateTimeProvider>());
}
[Fact]
public async Task EvaluateAsync_WhenUserExists_ShouldReturnTrue()
{
// Arrange
UserEntity user = _userEntityFixture.Create();
_mockUserRepository.GetByIdAsync(user.Id, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(user));
// Act
bool result = await _sut.EvaluateAsync(user.Id, null, CancellationToken.None);
// Assert
Assert.True(result);
}
[Fact]
public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<UserEntity?>(null));
// Act
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenGetUserReturnsFailure_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve user"));
// Act
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
// Assert
Assert.False(result);
}
[Fact]
public async Task EvaluateAsync_WhenUserEntityIsNull_ShouldReturnFalse()
{
// Arrange
Guid userId = Guid.NewGuid();
_mockUserRepository.GetByIdAsync(userId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result<UserEntity?>.Success(null));
// Act
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
// Assert
Assert.False(result);
}
}
@@ -0,0 +1,637 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
/// <summary>
/// Contains unit tests for the <see cref="MusicArtworkService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicArtworkServiceTests
{
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IPathService _mockPathService;
private readonly IHttpClientFactory _mockHttpClientFactory;
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
private readonly MusicArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly PathSegmentFixture _pathSegmentFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicArtworkServiceTests"/> class.
/// </summary>
public MusicArtworkServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books", musicDirectory: "music");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
_sut = new MusicArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
MockPathBuilding();
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
{
// Arrange
MockPathBuilding();
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
MockPathBuilding();
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album", _artworkDtoFixture.Create(localPath: sourcePath), null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
}
[Fact]
public void DeleteAlbumArtwork_WhenListingTheArtworkFilesFails_ShouldReturnTheError()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteAlbumArtwork_WhenCalled_ShouldDeleteEveryFileInTheAlbumDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
_mockFileProviderService.Received(1).DeleteFile(bookletFileId);
}
[Fact]
public void DeleteAlbumArtwork_WhenDeletingAFileFails_ShouldReturnTheErrorAndStopDeletingTheRemainingFiles()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
FileSystemPathId bookletFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "booklet-1.jpg"));
Error deleteError = Errors.FileSystemManagement.FileDeleteError;
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, bookletFileId]));
_mockFileProviderService.DeleteFile(coverFileId).Returns(deleteError);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(deleteError, result.FirstError);
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
_mockFileProviderService.DidNotReceive().DeleteFile(bookletFileId);
}
[Fact]
public void DeleteAlbumArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
{
// Arrange
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
// Assert
Assert.True(result.IsFailure);
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
}
[Fact]
public void DeleteAlbumArtwork_WhenBuildingTheDirectoryPathFails_ShouldReturnTheError()
{
// Arrange
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteAlbumArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", Guid.NewGuid(), "Artist", "Album");
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
byte[] uploadedBytes = [1, 2, 3, 4, 5, 6, 7, 8];
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.NotNull(capturedTemporaryPath);
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
Assert.EndsWith(".jpg", capturedTemporaryPath);
Assert.Equal(uploadedBytes, capturedBytes);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg");
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenAnArtworkStreamIsUploadedWithAReleaseType_ShouldStoreTheArtworkUnderTheReleaseTypeDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string releaseTypeName = "Single";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle, releaseTypeName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpg");
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", releaseTypeName, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).CopyFile(
Arg.Any<FileSystemPathId>(),
Arg.Is<FileSystemPathId>(pathId => pathId.Path == artworkDirectoryPath),
true);
}
[Fact]
public async Task SaveAlbumArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
});
await using MemoryStream artworkStream = new([1, 2, 3, 4]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, "cover.jpg", null, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
Assert.NotNull(capturedTemporaryPath);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.DidNotReceive().RenameFile(Arg.Any<FileSystemPathId>(), Arg.Any<string>());
}
[Theory]
[InlineData("cover")] // A name without an extension falls back to the .img extension.
[InlineData("")] // An empty name falls back to the .img extension.
[InlineData(null)] // A null name falls back to the .img extension.
public async Task SaveAlbumArtworkAsync_WhenTheUploadedFileNameHasNoExtension_ShouldBufferTheUploadWithTheImgExtension(string? fileName)
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid albumId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string albumTitle = "Test Album";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, albumId, libraryName, artistId, artistName, albumTitle);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.img")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"))));
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveAlbumArtworkAsync(libraryId, albumId, libraryName, artistId, artistName, albumTitle, artworkStream, fileName!, null, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.NotNull(capturedTemporaryPath);
Assert.EndsWith(".img", capturedTemporaryPath);
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenAnArtworkStreamIsUploaded_ShouldStoreItAsTheCoverAndDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
byte[] uploadedBytes = [9, 8, 7, 6, 5];
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.png");
string? capturedTemporaryPath = null;
byte[]? capturedBytes = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
capturedBytes = File.ReadAllBytes(capturedTemporaryPath);
return Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "upload.png")));
});
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.png")
.Returns(Result.From(_fileSystemPathIdFixture.Create(renamedFilePath)));
await using MemoryStream artworkStream = new(uploadedBytes);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value);
Assert.NotNull(capturedTemporaryPath);
Assert.StartsWith(Path.GetTempPath(), capturedTemporaryPath);
Assert.EndsWith(".png", capturedTemporaryPath);
Assert.Equal(uploadedBytes, capturedBytes);
Assert.False(File.Exists(capturedTemporaryPath));
_mockFileProviderService.Received(1).RenameFile(Arg.Any<FileSystemPathId>(), "cover.png");
}
[Fact]
public async Task SaveArtistArtworkAsync_WhenTheDownstreamStorageFails_ShouldStillDeleteTheTemporaryUpload()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid artistId = Guid.NewGuid();
string libraryName = "Test Library";
string artistName = "Test Artist";
string artworkDirectoryPath = BuildArtistArtworkDirectoryPath(libraryId, libraryName, artistId, artistName);
string? capturedTemporaryPath = null;
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.PNG));
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true)
.Returns(callInfo =>
{
capturedTemporaryPath = callInfo.ArgAt<FileSystemPathId>(0).Path;
return Error.Failure("FileSystem.Error", "Failed to copy the artwork");
});
await using MemoryStream artworkStream = new([1, 2, 3]);
// Act
Result<string> result = await _sut.SaveArtistArtworkAsync(libraryId, libraryName, artistId, artistName, artworkStream, "cover.png", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
Assert.NotNull(capturedTemporaryPath);
Assert.False(File.Exists(capturedTemporaryPath));
}
[Theory]
[InlineData(null)] // A null path is a no-op.
[InlineData("")] // An empty path is a no-op.
[InlineData(" ")] // A whitespace path is a no-op.
public void DeleteStoredArtwork_WhenThePathIsMissing_ShouldReturnDeletedWithoutTouchingTheFileSystem(string? artworkRelativePath)
{
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath!);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().FileExists(Arg.Any<FileSystemPathId>());
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileDoesNotExist_ShouldReturnDeleted()
{
// Arrange
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenTheFileExists_ShouldDeleteItAndReturnDeleted()
{
// Arrange
string artworkRelativePath = $"\\media\\music\\cover-{Guid.NewGuid():N}.jpg";
string expectedAbsolutePath = Path.Combine(AppContext.BaseDirectory, artworkRelativePath.TrimStart('\\'));
_mockFileProviderService.FileExists(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath))
.Returns(Result.From(true));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(Arg.Is<FileSystemPathId>(pathId => pathId.Path == expectedAbsolutePath));
}
[Fact]
public void DeleteStoredArtwork_WhenTheExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
string artworkRelativePath = "\\media\\music\\cover.jpg";
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteStoredArtwork_WhenDeletingTheFileFails_ShouldReturnTheError()
{
// Arrange
string artworkRelativePath = "\\media\\music\\cover.jpg";
Error error = Error.Failure("FileSystem.Error", "Failed to delete the artwork file");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>())
.Returns(error);
// Act
Result<Deleted> result = _sut.DeleteStoredArtwork(artworkRelativePath);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
_mockFileProviderService.Received(1).DeleteFile(Arg.Any<FileSystemPathId>());
}
/// <summary>
/// Stubs the path service so that building the artwork directory paths succeeds.
/// </summary>
private void MockPathBuilding()
{
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
}
/// <summary>
/// Stubs the path and file system services so that the artwork is stored into the given directory.
/// </summary>
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
{
MockPathBuilding();
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the album is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the album belongs to.</param>
/// <param name="albumId">The Id of the album.</param>
/// <param name="libraryName">The name of the media library the album belongs to.</param>
/// <param name="artistId">The Id of the artist of the album.</param>
/// <param name="artistName">The name of the artist of the album.</param>
/// <param name="albumTitle">The title of the album.</param>
/// <param name="releaseTypeName">Optional. The name of the release type directory the album is stored under.</param>
/// <returns>The expected file system path of the album artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid albumId, string libraryName, Guid artistId, string artistName, string albumTitle, string? releaseTypeName = null)
{
if (string.IsNullOrWhiteSpace(releaseTypeName))
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
$"{artistName}-{artistId}",
$"{albumTitle}-{albumId}");
}
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
$"{artistName}-{artistId}",
releaseTypeName,
$"{albumTitle}-{albumId}");
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the artist is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the artist belongs to.</param>
/// <param name="libraryName">The name of the media library the artist belongs to.</param>
/// <param name="artistId">The Id of the artist.</param>
/// <param name="artistName">The name of the artist.</param>
/// <returns>The expected file system path of the artist artwork directory.</returns>
private static string BuildArtistArtworkDirectoryPath(Guid libraryId, string libraryName, Guid artistId, string artistName)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"music",
$"{libraryName}-{libraryId}",
$"{artistName}-{artistId}");
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="AudioContainerResolver"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AudioContainerResolverTests
{
[Theory]
[InlineData(null, null)] // An absent mime type leaves the container unrecognized.
[InlineData("", null)] // An empty mime type leaves the container unrecognized.
[InlineData(" ", null)] // A blank mime type leaves the container unrecognized.
[InlineData("taglib/wav", "WAV")] // The taglib prefix is dropped and the container is upper cased.
[InlineData("taglib/png", "PNG")] // A container the resolver has no dedicated parser for still yields its name.
[InlineData("audio/x-wavpack", "X-WAVPACK")] // The last segment of a standard mime type names the container.
public void ResolveFromMimeType_WhenCalled_ShouldReturnTheContainerNamedByTheMimeType(string? mimeType, string? expectedContainer)
{
// Act
string? container = AudioContainerResolver.ResolveFromMimeType(mimeType);
// Assert
Assert.Equal(expectedContainer, container);
}
}
@@ -0,0 +1,156 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Metadata;
/// <summary>
/// Contains unit tests for the <see cref="MusicMetadataAggregator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMetadataAggregatorTests
{
private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new();
private readonly AlbumMetadataDtoFixture _albumMetadataDtoFixture = new();
private readonly AudioMetadataDtoFixture _audioMetadataDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new();
[Fact]
public void Merge_WhenMergingArtistMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
{
// Arrange
MediaContributorDto firstContributor = _mediaContributorDtoFixture.Create();
MediaContributorDto secondContributor = _mediaContributorDtoFixture.Create();
ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", includeCountry: false, contributors: [firstContributor], genres: []);
ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", contributors: [secondContributor], genres: []);
// Act
ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("First", merged.Name);
Assert.Equal("CA", merged.Country);
Assert.Equal(2, merged.Contributors!.Count);
Assert.Contains(merged.Contributors, contributor => contributor == firstContributor);
Assert.Contains(merged.Contributors, contributor => contributor == secondContributor);
}
[Fact]
public void Merge_WhenFirstArtistHasTheValue_ShouldNotTakeTheSecondValue()
{
// Arrange
ArtistMetadataDto first = _artistMetadataDtoFixture.Create(name: "First", country: "US", genres: [], contributors: []);
ArtistMetadataDto second = _artistMetadataDtoFixture.Create(name: "Second", country: "CA", genres: [], contributors: []);
// Act
ArtistMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("First", merged.Name);
Assert.Equal("US", merged.Country);
}
[Fact]
public void Merge_WhenMergingAlbumMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
{
// Arrange
AlbumMetadataDto first = _albumMetadataDtoFixture.Create(title: "First", includeBarcode: false, includeReleaseInfo: false);
AlbumMetadataDto second = _albumMetadataDtoFixture.Create(title: "Second", barcode: "1234567890123");
// Act
AlbumMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("First", merged.Title);
Assert.Equal("1234567890123", merged.Barcode);
Assert.NotNull(merged.ReleaseInfo);
}
[Fact]
public void Merge_WhenMergingAudioMetadata_ShouldGivePriorityToFirstAndFillMissingValuesFromSecond()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create(title: "First", includeDurationInSeconds: false);
AudioMetadataDto second = _audioMetadataDtoFixture.Create(title: "Second", durationInSeconds: 360);
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("First", merged.Title);
Assert.Equal(360, merged.DurationInSeconds);
}
[Fact]
public void Merge_WhenTheFirstAudioMetadataHasAContainer_ShouldKeepTheFirstContainer()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create(container: "MP3");
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("MP3", merged.Container);
}
[Fact]
public void Merge_WhenTheFirstAudioMetadataHasNoContainer_ShouldTakeTheSecondContainer()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create(includeContainer: false);
AudioMetadataDto second = _audioMetadataDtoFixture.Create(container: "FLAC");
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("FLAC", merged.Container);
}
[Fact]
public void Merge_WhenTheFirstMetadataHasOnlyAReleaseYearAndTheSecondHasAReleaseDate_ShouldDeriveTheYearFromTheDate()
{
// Arrange
// The tags of a compilation provide a release year without a full date, while MusicBrainz provides the original release date of the recording.
ReleaseInfoDto firstReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseYear: 1981);
ReleaseInfoDto secondReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(1975, 10, 31), originalReleaseYear: 1975);
AudioMetadataDto first = _audioMetadataDtoFixture.Create(releaseInfo: firstReleaseInfo);
AudioMetadataDto second = _audioMetadataDtoFixture.Create(releaseInfo: secondReleaseInfo);
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(first, second);
// Assert
// The merged date and year must describe the same point in time, otherwise the release information would be rejected when applied.
Assert.NotNull(merged.ReleaseInfo);
Assert.Equal(new DateOnly(1975, 10, 31), merged.ReleaseInfo!.OriginalReleaseDate);
Assert.Equal(1975, merged.ReleaseInfo.OriginalReleaseYear);
}
[Fact]
public void Merge_WhenBothAudioMetadataHaveIsrcs_ShouldUnionThemWithoutDuplicates()
{
// Arrange
AudioMetadataDto first = _audioMetadataDtoFixture.Create();
AudioMetadataDto second = _audioMetadataDtoFixture.Create();
AudioMetadataDto mergedInput = first with { Isrcs = [.. first.Isrcs!.Concat(second.Isrcs!)] };
// Act
AudioMetadataDto merged = MusicMetadataAggregator.Merge(mergedInput, second);
// Assert
Assert.Equal(mergedInput.Isrcs!.Select(isrc => isrc.Value).Distinct(StringComparer.OrdinalIgnoreCase).Count(), merged.Isrcs!.Count);
}
}
@@ -0,0 +1,444 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackDeliveryHandleService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackDeliveryHandleServiceTests
{
private readonly PlaybackDeliveryHandleService _sut;
private readonly PlaybackDeliveryHandleDtoFixture _playbackDeliveryHandleDtoFixture = new();
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PlaybackDeliveryHandleServiceTests"/> class.
/// </summary>
public PlaybackDeliveryHandleServiceTests()
{
_sut = new PlaybackDeliveryHandleService();
}
[Fact]
public void IssueDeliveryId_WhenCalled_ShouldReturnA32CharacterLowercaseHexadecimalHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string handle = _sut.IssueDeliveryId(delivery);
// Assert
Assert.Equal(32, handle.Length);
Assert.Matches("^[0-9a-f]{32}$", handle);
Assert.True(PlaybackDeliveryId.IsValid(handle));
}
[Fact]
public void IssueDeliveryId_WhenDeliveriesDiffer_ShouldReturnDistinctHandles()
{
// Arrange
PlaybackDeliveryHandleDto firstDelivery = CreateBaseDelivery();
PlaybackDeliveryHandleDto secondDelivery = CreateBaseDelivery();
// Act
string firstHandle = _sut.IssueDeliveryId(firstDelivery);
string secondHandle = _sut.IssueDeliveryId(secondDelivery);
// Assert
Assert.NotEqual(firstHandle, secondHandle);
}
[Fact]
public void IssueDeliveryId_WhenTheSameDeliveryIsIssuedAgain_ShouldReturnTheSameHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string firstHandle = _sut.IssueDeliveryId(delivery);
string secondHandle = _sut.IssueDeliveryId(delivery);
// Assert
Assert.Equal(firstHandle, secondHandle);
}
[Fact]
public void IssueDeliveryId_WhenAnEqualDeliveryIsIssuedAgainAtThePerUserLimit_ShouldReuseTheExistingHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Fill the rest of the per user bound with distinct deliveries, so the next issue would evict this one if it did not reuse it.
for (int index = 0; index < 63; index++)
_sut.IssueDeliveryId(CreateDeliveryFor(delivery.Request.UserId));
PlaybackDeliveryHandleDto equalDelivery = delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots] } };
// Act
string reusedHandle = _sut.IssueDeliveryId(equalDelivery);
// Assert
Assert.Equal(handle, reusedHandle);
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
Assert.False(result.IsFailure);
Assert.Same(delivery, result.Value);
}
public static TheoryData<DeliveryVariation> SignatureVariations => new()
{
DeliveryVariation.UserId,
DeliveryVariation.TrackId,
DeliveryVariation.LibraryId,
DeliveryVariation.AlbumId,
DeliveryVariation.ArtistId,
DeliveryVariation.Mode,
DeliveryVariation.Shape,
DeliveryVariation.SourceContainer,
DeliveryVariation.SourceContainerNull,
DeliveryVariation.Container,
DeliveryVariation.Codec,
DeliveryVariation.SegmentDurationSeconds,
DeliveryVariation.DurationInSeconds,
DeliveryVariation.Bitrate,
DeliveryVariation.BitrateNull,
DeliveryVariation.SampleRate,
DeliveryVariation.Channels,
DeliveryVariation.BitDepth,
DeliveryVariation.BitDepthNull,
DeliveryVariation.Quality,
DeliveryVariation.SourcePath,
DeliveryVariation.SourceLength,
DeliveryVariation.SourceLastModifiedUtc,
DeliveryVariation.AllowedRoots
};
[Theory]
[MemberData(nameof(SignatureVariations))]
public void IssueDeliveryId_WhenOneSignatureInputChanges_ShouldReturnADifferentHandle(DeliveryVariation variation)
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
PlaybackDeliveryHandleDto variedDelivery = Vary(delivery, variation);
// Act
string variedHandle = _sut.IssueDeliveryId(variedDelivery);
// Assert
Assert.NotEqual(handle, variedHandle);
}
[Theory]
[InlineData(null)] // An absent handle cannot address a delivery.
[InlineData("")] // An empty handle cannot address a delivery.
[InlineData(" ")] // A whitespace handle cannot address a delivery.
[InlineData("0123456789abcdef0123456789abcdef")] // A well formed handle that was never issued.
public void GetDelivery_WhenTheHandleIsMissingOrUnknown_ShouldReturnPlaybackDeliveryNotFoundError(string? deliveryId)
{
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(deliveryId, Guid.NewGuid(), Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleWasIssuedToAnotherUser_ShouldReturnPlaybackDeliveryNotFoundError()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, Guid.NewGuid(), delivery.Request.TrackId);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleDescribesAnotherTrack_ShouldReturnPlaybackDeliveryNotFoundError()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, Guid.NewGuid());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryNotFound, result.FirstError);
}
[Fact]
public void GetDelivery_WhenTheHandleWasIssuedToTheUserForTheTrack_ShouldReturnTheIssuedDelivery()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
string handle = _sut.IssueDeliveryId(delivery);
// Act
Result<PlaybackDeliveryHandleDto> result = _sut.GetDelivery(handle, delivery.Request.UserId, delivery.Request.TrackId);
// Assert
Assert.False(result.IsFailure);
Assert.Same(delivery, result.Value);
Assert.Equal(delivery.Request.TrackId, result.Value.Request.TrackId);
Assert.Equal(delivery.Request.UserId, result.Value.Request.UserId);
Assert.Equal(delivery.Shape, result.Value.Shape);
Assert.Equal(delivery.LibraryId, result.Value.LibraryId);
Assert.Equal(delivery.AlbumId, result.Value.AlbumId);
Assert.Equal(delivery.ArtistId, result.Value.ArtistId);
}
[Fact]
public void IssueDeliveryId_WhenAUserExceedsThePerUserLimit_ShouldEvictOnlyTheOldestHandleOfThatUser()
{
// Arrange
Guid userId = Guid.NewGuid();
Guid otherUserId = Guid.NewGuid();
PlaybackDeliveryHandleDto otherUserDelivery = CreateDeliveryFor(otherUserId);
string otherUserHandle = _sut.IssueDeliveryId(otherUserDelivery);
List<(string Handle, Guid TrackId)> handles = [];
for (int index = 0; index < 64; index++)
{
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
handles.Add((_sut.IssueDeliveryId(delivery), delivery.Request.TrackId));
}
// Act
PlaybackDeliveryHandleDto newestDelivery = CreateDeliveryFor(userId);
string newestHandle = _sut.IssueDeliveryId(newestDelivery);
// Assert
Assert.True(_sut.GetDelivery(handles[0].Handle, userId, handles[0].TrackId).IsFailure);
for (int index = 1; index < handles.Count; index++)
Assert.True(_sut.GetDelivery(handles[index].Handle, userId, handles[index].TrackId).IsSuccess);
Assert.True(_sut.GetDelivery(newestHandle, userId, newestDelivery.Request.TrackId).IsSuccess);
Assert.True(_sut.GetDelivery(otherUserHandle, otherUserId, otherUserDelivery.Request.TrackId).IsSuccess);
}
[Fact]
public void IssueDeliveryId_WhenTheGlobalLimitIsExceeded_ShouldEvictOnlyTheOldestHandle()
{
// Arrange
PlaybackDeliveryHandleService sut = new();
Guid[] users = [.. Enumerable.Range(0, 400).Select(_ => Guid.NewGuid())];
string? oldestHandle = null;
Guid oldestUserId = Guid.Empty;
Guid oldestTrackId = Guid.Empty;
string? secondOldestHandle = null;
Guid secondOldestUserId = Guid.Empty;
Guid secondOldestTrackId = Guid.Empty;
string? newestHandle = null;
Guid newestUserId = Guid.Empty;
Guid newestTrackId = Guid.Empty;
for (int index = 0; index < 20_000; index++)
{
// The per user bound is 64, so each user is given exactly 64 deliveries and never triggers a per user eviction.
Guid userId = users[index / 64];
PlaybackDeliveryHandleDto delivery = CreateDeliveryFor(userId);
string handle = sut.IssueDeliveryId(delivery);
if (index == 0)
{
oldestHandle = handle;
oldestUserId = userId;
oldestTrackId = delivery.Request.TrackId;
}
else if (index == 1)
{
secondOldestHandle = handle;
secondOldestUserId = userId;
secondOldestTrackId = delivery.Request.TrackId;
}
if (index == 19_999)
{
newestHandle = handle;
newestUserId = userId;
newestTrackId = delivery.Request.TrackId;
}
}
PlaybackDeliveryHandleDto extraDelivery = CreateDeliveryFor(Guid.NewGuid());
// Act
string extraHandle = sut.IssueDeliveryId(extraDelivery);
// Assert
Assert.True(sut.GetDelivery(oldestHandle, oldestUserId, oldestTrackId).IsFailure);
Assert.True(sut.GetDelivery(secondOldestHandle, secondOldestUserId, secondOldestTrackId).IsSuccess);
Assert.True(sut.GetDelivery(newestHandle, newestUserId, newestTrackId).IsSuccess);
Assert.True(sut.GetDelivery(extraHandle, extraDelivery.Request.UserId, extraDelivery.Request.TrackId).IsSuccess);
}
[Fact]
public async Task IssueDeliveryId_WhenTheSameDeliveryIsIssuedConcurrently_ShouldReturnOneIdenticalHandle()
{
// Arrange
PlaybackDeliveryHandleDto delivery = CreateBaseDelivery();
// Act
string[] handles = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() => _sut.IssueDeliveryId(delivery))));
// Assert
Assert.Single(handles.Distinct());
Assert.True(_sut.GetDelivery(handles[0], delivery.Request.UserId, delivery.Request.TrackId).IsSuccess);
}
[Fact]
public async Task IssueDeliveryId_WhenDifferentDeliveriesAreIssuedConcurrently_ShouldMakeEveryHandleResolvable()
{
// Arrange
PlaybackDeliveryHandleDto[] deliveries = [.. Enumerable.Range(0, 32).Select(_ => CreateDeliveryFor(Guid.NewGuid()))];
// Act
string[] handles = await Task.WhenAll(deliveries.Select(delivery => Task.Run(() => _sut.IssueDeliveryId(delivery))));
// Assert
Assert.Equal(deliveries.Length, handles.Distinct().Count());
for (int index = 0; index < deliveries.Length; index++)
Assert.True(_sut.GetDelivery(handles[index], deliveries[index].Request.UserId, deliveries[index].Request.TrackId).IsSuccess);
}
/// <summary>
/// The single input of the delivery signature that a variation changes.
/// </summary>
public enum DeliveryVariation
{
UserId,
TrackId,
LibraryId,
AlbumId,
ArtistId,
Mode,
Shape,
SourceContainer,
SourceContainerNull,
Container,
Codec,
SegmentDurationSeconds,
DurationInSeconds,
Bitrate,
BitrateNull,
SampleRate,
Channels,
BitDepth,
BitDepthNull,
Quality,
SourcePath,
SourceLength,
SourceLastModifiedUtc,
AllowedRoots
}
/// <summary>
/// Creates a delivery with every signature input explicitly pinned.
/// </summary>
/// <returns>The created delivery.</returns>
private PlaybackDeliveryHandleDto CreateBaseDelivery()
{
return _playbackDeliveryHandleDtoFixture.Create(
request: CreateRequest(userId: Guid.NewGuid(), trackId: Guid.NewGuid()),
shape: PlaybackDeliveryShape.TimeAddressedSegments,
libraryId: Guid.Parse("11111111-1111-1111-1111-111111111111"),
albumId: Guid.Parse("22222222-2222-2222-2222-222222222222"),
artistId: Guid.Parse("33333333-3333-3333-3333-333333333333"));
}
/// <summary>
/// Creates a delivery for a user whose track is unique to the delivery.
/// </summary>
/// <param name="userId">The Id of the user the delivery is issued to.</param>
/// <returns>The created delivery.</returns>
private PlaybackDeliveryHandleDto CreateDeliveryFor(Guid userId)
{
return _playbackDeliveryHandleDtoFixture.Create(
request: CreateRequest(userId: userId, trackId: Guid.NewGuid()),
shape: PlaybackDeliveryShape.TimeAddressedSegments,
libraryId: Guid.NewGuid(),
albumId: Guid.NewGuid(),
artistId: Guid.NewGuid());
}
/// <summary>
/// Changes exactly one input of the delivery signature.
/// </summary>
/// <param name="delivery">The delivery to vary.</param>
/// <param name="variation">The input to change.</param>
/// <returns>The varied delivery.</returns>
private static PlaybackDeliveryHandleDto Vary(PlaybackDeliveryHandleDto delivery, DeliveryVariation variation)
{
return variation switch
{
DeliveryVariation.UserId => delivery with { Request = delivery.Request with { UserId = Guid.NewGuid() } },
DeliveryVariation.TrackId => delivery with { Request = delivery.Request with { TrackId = Guid.NewGuid() } },
DeliveryVariation.LibraryId => delivery with { LibraryId = Guid.NewGuid() },
DeliveryVariation.AlbumId => delivery with { AlbumId = Guid.NewGuid() },
DeliveryVariation.ArtistId => delivery with { ArtistId = Guid.NewGuid() },
DeliveryVariation.Mode => delivery with { Request = delivery.Request with { Mode = PlaybackDeliveryMode.Remux } },
DeliveryVariation.Shape => delivery with { Shape = PlaybackDeliveryShape.ByteRangeSeekable },
DeliveryVariation.SourceContainer => delivery with { Request = delivery.Request with { SourceContainer = "WAV" } },
DeliveryVariation.SourceContainerNull => delivery with { Request = delivery.Request with { SourceContainer = null } },
DeliveryVariation.Container => delivery with { Request = delivery.Request with { Container = "AAC" } },
DeliveryVariation.Codec => delivery with { Request = delivery.Request with { Codec = "AAC" } },
DeliveryVariation.SegmentDurationSeconds => delivery with { Request = delivery.Request with { SegmentDurationSeconds = 10 } },
DeliveryVariation.DurationInSeconds => delivery with { Request = delivery.Request with { DurationInSeconds = 300 } },
DeliveryVariation.Bitrate => delivery with { Request = delivery.Request with { Bitrate = 320 } },
DeliveryVariation.BitrateNull => delivery with { Request = delivery.Request with { Bitrate = null } },
DeliveryVariation.SampleRate => delivery with { Request = delivery.Request with { SampleRate = 96000 } },
DeliveryVariation.Channels => delivery with { Request = delivery.Request with { Channels = 6 } },
DeliveryVariation.BitDepth => delivery with { Request = delivery.Request with { BitDepth = 16 } },
DeliveryVariation.BitDepthNull => delivery with { Request = delivery.Request with { BitDepth = null } },
DeliveryVariation.Quality => delivery with { Request = delivery.Request with { Quality = PlaybackStreamingQuality.Low } },
DeliveryVariation.SourcePath => delivery with { Request = delivery.Request with { SourcePath = "/music/incoming/other.flac" } },
DeliveryVariation.SourceLength => delivery with { Request = delivery.Request with { SourceLength = 999 } },
DeliveryVariation.SourceLastModifiedUtc => delivery with { Request = delivery.Request with { SourceLastModifiedUtc = new DateTime(2026, 2, 3, 4, 5, 6, DateTimeKind.Utc) } },
DeliveryVariation.AllowedRoots => delivery with { Request = delivery.Request with { AllowedRoots = [.. delivery.Request.AllowedRoots.Take(1), "/music/other"] } },
_ => throw new ArgumentOutOfRangeException(nameof(variation), variation, "Unsupported delivery variation.")
};
}
/// <summary>
/// Creates a normalization request with every signature input explicitly pinned.
/// </summary>
/// <param name="userId">The Id of the user the delivery is issued to.</param>
/// <param name="trackId">The Id of the track the delivery describes.</param>
/// <returns>The created request.</returns>
private NormalizedTrackRequestDto CreateRequest(Guid userId, Guid trackId)
{
return _normalizedTrackRequestDtoFixture.Create(
trackId: trackId,
userId: userId,
sourcePath: "/music/library/track.flac",
allowedRoots: ["/music/library", "/music/incoming"],
sourceContainer: "FLAC",
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
segmentDurationSeconds: 6,
durationInSeconds: 245,
bitrate: 900,
sampleRate: 48000,
channels: 2,
bitDepth: 24,
quality: PlaybackStreamingQuality.High,
sourceLength: 123456,
sourceLastModifiedUtc: new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc));
}
}
@@ -0,0 +1,199 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackFormatCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackFormatCatalogTests
{
[Fact]
public void Formats_WhenRead_ShouldExposeTheDocumentedCanonicalContainerAndCodecPairsInPreferenceOrder()
{
// Arrange
(string Container, string Codec)[] expectedPairs =
[
("MP4", "AAC"), // The preferred container of the preferred codec.
("AAC", "AAC"), // The second container of the preferred codec.
("OGG", "OPUS"), // The preferred lossy codec after AAC.
("MP3", "MP3"), // The compatibility codec.
("OGG", "VORBIS"), // The second lossy codec in OGG.
("FLAC", "FLAC"), // The lossless codec.
("WAV", "PCM") // The uncompressed codec.
];
// Act
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
// Assert
Assert.Equal(expectedPairs, result.Select(format => (format.Container, format.Codec)));
}
[Fact]
public void TranscodeCodecPreference_WhenRead_ShouldListEachCodecOnceInOrderOfFirstAppearanceInFormats()
{
// Arrange
List<string> expectedCodecs = [];
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
if (!expectedCodecs.Contains(format.Codec, StringComparer.OrdinalIgnoreCase))
expectedCodecs.Add(format.Codec);
// Act
IReadOnlyList<string> result = PlaybackFormatCatalog.TranscodeCodecPreference;
// Assert
Assert.Equal(expectedCodecs, result);
Assert.Equal(["AAC", "OPUS", "MP3", "VORBIS", "FLAC", "PCM"], result);
Assert.Equal(result.Count, result.Distinct(StringComparer.OrdinalIgnoreCase).Count());
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldGroupTheContainersPerCodecInCatalogOrder()
{
// Arrange
Dictionary<string, List<string>> expectedContainersByCodec = new(StringComparer.OrdinalIgnoreCase);
foreach (NormalizedAudioFormatDto format in PlaybackFormatCatalog.Formats)
{
if (!expectedContainersByCodec.TryGetValue(format.Codec, out List<string>? containers))
{
containers = [];
expectedContainersByCodec[format.Codec] = containers;
}
containers.Add(format.Container);
}
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
Assert.Equal(expectedContainersByCodec.Count, result.Count);
foreach (KeyValuePair<string, List<string>> expectedEntry in expectedContainersByCodec)
{
Assert.True(result.TryGetValue(expectedEntry.Key, out IReadOnlyList<string>? containers));
Assert.Equal(expectedEntry.Value, containers);
}
Assert.Equal(["MP4", "AAC"], result["AAC"]); // The preferred codec has two producible containers, in preference order.
Assert.Equal(["OGG"], result["OPUS"]);
Assert.Equal(["OGG"], result["VORBIS"]);
Assert.Equal(["MP3"], result["MP3"]);
Assert.Equal(["FLAC"], result["FLAC"]);
Assert.Equal(["WAV"], result["PCM"]);
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldNotRepeatAContainerWithinACodec()
{
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
foreach (IReadOnlyList<string> containers in result.Values)
Assert.Equal(containers.Count, containers.Distinct(StringComparer.OrdinalIgnoreCase).Count());
}
[Fact]
public void ProducibleContainersByCodec_WhenRead_ShouldOnlyContainPairsThatExistInTheCatalog()
{
// Act
IReadOnlyDictionary<string, IReadOnlyList<string>> result = PlaybackFormatCatalog.ProducibleContainersByCodec;
// Assert
foreach (KeyValuePair<string, IReadOnlyList<string>> entry in result)
foreach (string container in entry.Value)
Assert.Contains(PlaybackFormatCatalog.Formats, format =>
string.Equals(format.Codec, entry.Key, StringComparison.OrdinalIgnoreCase) &&
string.Equals(format.Container, container, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void FormatsByPair_WhenRead_ShouldContainExactlyOneEntryPerCatalogFormat()
{
// Act
IReadOnlyDictionary<string, NormalizedAudioFormatDto> result = PlaybackFormatCatalog.FormatsByPair;
// Assert
Assert.Equal(PlaybackFormatCatalog.Formats.Count, result.Count);
Assert.All(PlaybackFormatCatalog.Formats, format =>
{
string pairKey = PlaybackFormatCatalog.BuildPairKey(format.Container, format.Codec);
Assert.True(result.TryGetValue(pairKey, out NormalizedAudioFormatDto? indexedFormat));
Assert.Equal(format, indexedFormat);
});
}
[Theory]
[InlineData("mp4/aac", "MP4", "AAC")] // The canonical pair in lower case.
[InlineData("Mp4/Aac", "MP4", "AAC")] // The canonical pair in mixed case.
[InlineData("aac/aac", "AAC", "AAC")] // The second format in the catalog, in lower case.
public void FormatsByPair_WhenLookedUpWithDifferentCasing_ShouldReturnTheCatalogFormat(string pairKey, string expectedContainer, string expectedCodec)
{
// Act
bool found = PlaybackFormatCatalog.FormatsByPair.TryGetValue(pairKey, out NormalizedAudioFormatDto? result);
// Assert
Assert.True(found);
Assert.NotNull(result);
Assert.Equal(expectedContainer, result.Container);
Assert.Equal(expectedCodec, result.Codec);
}
[Fact]
public void BuildPairKey_WhenTheInputsArePaddedAndDifferentlyCased_ShouldTrimAndUppercaseThem()
{
// Act
string result = PlaybackFormatCatalog.BuildPairKey(" mp4 ", "\taAc ");
// Assert
Assert.Equal("MP4/AAC", result);
}
[Fact]
public void BuildPairKey_WhenTheInputsDifferOnlyInCasingAndPadding_ShouldProduceTheSameKey()
{
// Act
string firstResult = PlaybackFormatCatalog.BuildPairKey("mp4", "aac");
string secondResult = PlaybackFormatCatalog.BuildPairKey(" MP4 ", " AAC ");
// Assert
Assert.Equal(firstResult, secondResult);
}
[Theory]
[InlineData(null, null, "/")] // Both parts are absent.
[InlineData("", "", "/")] // Both parts are empty.
[InlineData(" ", " ", "/")] // Both parts are white space.
[InlineData(null, "aac", "/AAC")] // Only the container is absent.
[InlineData("mp4", null, "MP4/")] // Only the codec is absent.
public void BuildPairKey_WhenAContainerOrCodecIsNullOrEmpty_ShouldProduceTheSlashSeparatedFormWithoutThrowing(string? container, string? codec, string expectedKey)
{
// Act
string result = PlaybackFormatCatalog.BuildPairKey(container!, codec!);
// Assert
Assert.Equal(expectedKey, result);
}
[Fact]
public void Formats_WhenRead_ShouldExposeANonEmptyMuxerALeadingDotExtensionAndANonEmptyEncoderForEveryFormat()
{
// Act
IReadOnlyList<NormalizedAudioFormatDto> result = PlaybackFormatCatalog.Formats;
// Assert
Assert.All(result, format =>
{
Assert.False(string.IsNullOrWhiteSpace(format.MuxerName));
Assert.StartsWith(".", format.FileExtension, StringComparison.Ordinal);
Assert.True(format.FileExtension.Length > 1);
Assert.False(string.IsNullOrWhiteSpace(format.EncoderName));
});
}
}
@@ -0,0 +1,283 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="PlaybackFormatService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackFormatServiceTests
{
private readonly PlaybackFormatService _sut;
private readonly PlaybackSourceFormatDtoFixture _playbackSourceFormatDtoFixture = new();
private readonly PlaybackCapabilityDtoFixture _playbackCapabilityDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PlaybackFormatServiceTests"/> class.
/// </summary>
public PlaybackFormatServiceTests()
{
_sut = new PlaybackFormatService();
}
[Fact]
public void DecideDelivery_WhenPlayerAdvertisesTheStoredFormat_ShouldReturnDirectPlay()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "FLAC", codec: "FLAC");
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
Assert.Equal("FLAC", result.Value.Container);
Assert.Equal("FLAC", result.Value.Codec);
Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, result.Value.Shape);
Assert.Equal(0, result.Value.SegmentDurationSeconds);
}
[Fact]
public void DecideDelivery_WhenPlayerDecodesTheCodecButNotTheContainer_ShouldReturnRemux()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
IReadOnlyList<PlaybackCapabilityDto> capabilities =
[
_playbackCapabilityDtoFixture.Create(container: "WAV", codec: "PCM"),
_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC")
];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
Assert.Equal("WAV", result.Value.Container);
Assert.Equal("PCM", result.Value.Codec);
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
Assert.Equal(6, result.Value.SegmentDurationSeconds);
}
[Fact]
public void DecideDelivery_WhenPlayerCannotDecodeTheStoredCodec_ShouldReturnTranscode()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "WMA", codec: "WMA");
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
Assert.Equal("MP3", result.Value.Container);
Assert.Equal("MP3", result.Value.Codec);
Assert.Equal(PlaybackDeliveryShape.TimeAddressedSegments, result.Value.Shape);
Assert.Equal(6, result.Value.SegmentDurationSeconds);
}
[Fact]
public void DecideDelivery_WhenTheDefaultCapabilitiesAreUsed_ShouldReturnDirectPlay()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: "MP3");
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
}
[Fact]
public void DecideDelivery_WhenDefaultCapabilitiesAreUsedForAnAacTrackInMp4_ShouldReturnRemuxToRawAac()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP4", codec: "AAC");
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, PlaybackCapabilitiesParser.Default);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
Assert.Equal("AAC", result.Value.Container);
Assert.Equal("AAC", result.Value.Codec);
}
[Theory]
[InlineData("MP3", "MPEG-1 Layer 3", "MP3")] // The free form description of an MPEG-1 Layer 3 stream.
[InlineData("MP3", "MP3", "MP3")] // A codec that is already named canonically.
[InlineData("FLAC", "Flac", "FLAC")] // The description of a FLAC stream.
[InlineData("OGG", "Vorbis I", "VORBIS")] // The description of a Vorbis stream.
[InlineData("OGG", "Opus", "OPUS")] // The description of an Opus stream.
[InlineData("MP4", "Apple Lossless", "ALAC")] // The description of an Apple Lossless stream.
[InlineData("AAC", "MPEG-4 AAC", "AAC")] // A description naming both MPEG and AAC is AAC, not MP3.
[InlineData("WAV", "PCM", "PCM")] // The description of an uncompressed stream.
[InlineData("WAV", "Uncompressed", "PCM")] // Another description of an uncompressed stream.
[InlineData("WMA", "Windows Media Audio", "WMA")] // The description of a Windows Media stream.
public void DecideDelivery_WhenTheStoredCodecDescriptionIsRecognizable_ShouldCanonicalizeItAndDirectPlay(string container, string codecDescription, string canonicalCodec)
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: container, codec: codecDescription);
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: container, codec: canonicalCodec)];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.DirectPlay, result.Value.Mode);
Assert.Equal(canonicalCodec, result.Value.Codec);
}
[Theory]
[InlineData("MPEG-1 Layer 2")] // MP2 shares the MP3 container but an MP3 decoder cannot decode it.
[InlineData("MPEG-1 Layer 1")] // MP1 shares the MP3 container but an MP3 decoder cannot decode it.
[InlineData("MPEG-4 Audio")] // A description that names no decodable codec is not mistaken for MP3.
public void DecideDelivery_WhenAnMpegDescriptionIsNotLayer3_ShouldReturnTranscode(string codecDescription)
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MP3", codec: codecDescription);
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
}
[Theory]
[InlineData(null, null)] // An absent probe result names no codec.
[InlineData("", "")] // An empty probe result names no codec.
[InlineData("MP3", "AC-3")] // A codec description the server does not recognize.
public void DecideDelivery_WhenTheStoredFormatIsUnknown_ShouldReturnTranscode(string? container, string? codec)
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(
container: container,
codec: codec,
includeContainer: container is not null,
includeCodec: codec is not null);
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "MP3", codec: "MP3")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
}
[Fact]
public void DecideDelivery_WhenSeveralProducibleCodecsAreAdvertised_ShouldTranscodeToTheMostPreferredOne()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "OGG", codec: "OPUS");
IReadOnlyList<PlaybackCapabilityDto> capabilities =
[
_playbackCapabilityDtoFixture.Create(container: "FLAC", codec: "FLAC"),
_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")
];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Transcode, result.Value.Mode);
Assert.Equal("AAC", result.Value.Codec);
}
[Fact]
public void DecideDelivery_WhenSeveralContainersAreAdvertisedForTheSameCodec_ShouldRemuxToThePreferredContainer()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
IReadOnlyList<PlaybackCapabilityDto> capabilities =
[
_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC"),
_playbackCapabilityDtoFixture.Create(container: "MP4", codec: "AAC")
];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
Assert.Equal("MP4", result.Value.Container);
Assert.Equal("AAC", result.Value.Codec);
}
[Fact]
public void DecideDelivery_WhenThePreferredContainerForTheCodecIsNotAdvertised_ShouldRemuxToTheOtherProducibleContainer()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "MATROSKA", codec: "AAC");
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "AAC", codec: "AAC")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
Assert.Equal("AAC", result.Value.Container);
Assert.Equal("AAC", result.Value.Codec);
}
[Fact]
public void DecideDelivery_WhenThePlayerNamesAContainerTheServerDoesNotProduce_ShouldDeliverTheServerContainer()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
IReadOnlyList<PlaybackCapabilityDto> capabilities =
[
_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM"),
_playbackCapabilityDtoFixture.Create(container: "wav", codec: "pcm")
];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsSuccess);
Assert.Equal(PlaybackDeliveryMode.Remux, result.Value.Mode);
Assert.Equal("WAV", result.Value.Container);
Assert.Equal("PCM", result.Value.Codec);
}
[Fact]
public void DecideDelivery_WhenThePlayerOnlyNamesContainersTheServerDoesNotProduce_ShouldReturnNoSupportedPlaybackFormat()
{
// Arrange
PlaybackSourceFormatDto sourceFormat = _playbackSourceFormatDtoFixture.Create(container: "AIFF", codec: "PCM");
IReadOnlyList<PlaybackCapabilityDto> capabilities = [_playbackCapabilityDtoFixture.Create(container: "evil;$(x)", codec: "PCM")];
// Act
Result<PlaybackDeliveryDecisionDto> result = _sut.DecideDelivery(sourceFormat, capabilities);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NoSupportedPlaybackFormat, result.FirstError);
}
}
@@ -0,0 +1,207 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Abstractions;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="TrackNormalizationService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackNormalizationServiceTests : IDisposable
{
private readonly TrackNormalizationService _sut;
private readonly NormalizedTrackRequestDtoFixture _normalizedTrackRequestDtoFixture = new();
private readonly TranscodingSettingsDtoFixture _transcodingSettingsDtoFixture = new();
private readonly string _sandboxRoot;
private readonly string _cacheDirectory;
private readonly string _sourceRoot;
private readonly string _sourcePath;
private readonly long _sourceLength;
private readonly DateTime _sourceLastModifiedUtc;
/// <summary>
/// Initializes a new instance of the <see cref="TrackNormalizationServiceTests"/> class.
/// </summary>
public TrackNormalizationServiceTests()
{
_sandboxRoot = Path.Combine(Path.GetTempPath(), "lumina-track-normalization-tests-" + Guid.NewGuid().ToString("N"));
_cacheDirectory = Path.Combine(_sandboxRoot, "cache");
_sourceRoot = Path.Combine(_sandboxRoot, "source");
_sourcePath = Path.Combine(_sourceRoot, "track.flac");
Directory.CreateDirectory(_cacheDirectory);
Directory.CreateDirectory(_sourceRoot);
File.WriteAllBytes(_sourcePath, new byte[512]);
_sourceLength = new FileInfo(_sourcePath).Length;
_sourceLastModifiedUtc = File.GetLastWriteTimeUtc(_sourcePath);
// The real path service is used, with the real path strategy of the current platform, so containment follows the file system rules of the host.
IPlatformContext platformContext = Substitute.For<IPlatformContext>();
IPathStrategy pathStrategy = OperatingSystem.IsWindows()
? new WindowsPathStrategy(new FileSystem())
: new UnixPathStrategy(new FileSystem());
platformContext.PathStrategy.Returns(pathStrategy);
IPlatformContextManager platformContextManager = Substitute.For<IPlatformContextManager>();
platformContextManager.GetCurrentContext().Returns(platformContext);
IPathService pathService = new PathService(platformContextManager);
TranscodingSettingsDto settings = _transcodingSettingsDtoFixture.Create(
ffmpegPath: Path.Combine(_sandboxRoot, "missing-ffmpeg"),
maxConcurrentJobs: 2,
maxConcurrentJobsPerUser: 1,
maxCacheBytes: 100 * 1024 * 1024,
jobTimeoutSeconds: 60,
evictionGraceSeconds: 10,
cacheDirectory: _cacheDirectory);
TranscodingToolchainStatus toolchainStatus = new();
_sut = new TrackNormalizationService(Options.Create(settings), NullLogger<TrackNormalizationService>.Instance, pathService, toolchainStatus);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheUserIdIsEmpty_ShouldReturnNormalizationFailedError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(userId: Guid.Empty);
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationFailed, result.FirstError);
}
[Theory]
[InlineData(true)] // The source file length no longer matches the declared delivery.
[InlineData(false)] // The source file modification time no longer matches the declared delivery.
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileChangedSinceTheDeliveryWasDeclared_ShouldReturnPlaybackDeliveryChangedError(bool isLengthChanged)
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(
sourceLength: isLengthChanged ? _sourceLength + 1 : _sourceLength,
sourceLastModifiedUtc: isLengthChanged ? _sourceLastModifiedUtc : _sourceLastModifiedUtc.AddMinutes(-1));
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.PlaybackDeliveryChanged, result.FirstError);
}
[Fact(Skip = "Production bug: a missing source file inside an allowed root throws FileNotFoundException from HasReparsePointBelow (File.GetAttributes on the leaf) instead of returning Errors.Music.TrackFileNotFound. The exception escapes GetOrCreateNormalizedTrackAsync, so the contract of the method is violated for a track deleted between the manifest and the first segment request.")]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourceFileDoesNotExist_ShouldReturnTrackFileNotFoundError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(sourcePath: Path.Combine(_sourceRoot, "missing.flac"));
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheSourcePathIsOutsideEveryAllowedRoot_ShouldReturnTrackFileNotFoundError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest(allowedRoots: [Path.Combine(_sandboxRoot, "other")]);
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError);
}
[Fact]
public async Task GetOrCreateNormalizedTrackAsync_WhenTheServiceIsDisposed_ShouldReturnNormalizationUnavailableError()
{
// Arrange
NormalizedTrackRequestDto request = CreateRequest();
_sut.Dispose();
// Act
Result<NormalizedTrackDto> result = await _sut.GetOrCreateNormalizedTrackAsync(request, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Playback.NormalizationUnavailable, result.FirstError);
}
/// <summary>
/// Releases the service and the temporary directories of the test.
/// </summary>
public void Dispose()
{
_sut.Dispose();
try
{
if (Directory.Exists(_sandboxRoot))
Directory.Delete(_sandboxRoot, recursive: true);
}
catch (IOException)
{
// A temporary directory that cannot be removed does not fail the test.
}
}
/// <summary>
/// Creates a normalization request that matches the source file of the test.
/// </summary>
/// <param name="userId">The Id of the user whose request starts the production.</param>
/// <param name="sourcePath">The file system path of the stored audio file of the track.</param>
/// <param name="allowedRoots">The content locations the source path is allowed to be inside.</param>
/// <param name="sourceLength">The length the source file had when the delivery was declared, in bytes.</param>
/// <param name="sourceLastModifiedUtc">The last modification time the source file had when the delivery was declared.</param>
/// <returns>The created request.</returns>
private NormalizedTrackRequestDto CreateRequest(
Guid? userId = null,
string? sourcePath = null,
IReadOnlyList<string>? allowedRoots = null,
long? sourceLength = null,
DateTime? sourceLastModifiedUtc = null)
{
return _normalizedTrackRequestDtoFixture.Create(
trackId: Guid.NewGuid(),
userId: userId ?? Guid.NewGuid(),
sourcePath: sourcePath ?? _sourcePath,
allowedRoots: allowedRoots ?? [_sourceRoot],
sourceContainer: "FLAC",
mode: PlaybackDeliveryMode.Transcode,
container: "MP3",
codec: "MP3",
segmentDurationSeconds: 6,
durationInSeconds: 120,
bitrate: 900,
sampleRate: 44100,
channels: 2,
bitDepth: 16,
quality: PlaybackStreamingQuality.Auto,
sourceLength: sourceLength ?? _sourceLength,
sourceLastModifiedUtc: sourceLastModifiedUtc ?? _sourceLastModifiedUtc);
}
}
@@ -0,0 +1,141 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Contains unit tests for the <see cref="TranscodingToolchainStatus"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TranscodingToolchainStatusTests
{
private readonly TranscodingToolchainStatus _sut;
private readonly IReadOnlyList<string> _catalogEncoderNames;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingToolchainStatusTests"/> class.
/// </summary>
public TranscodingToolchainStatusTests()
{
_sut = new TranscodingToolchainStatus();
_catalogEncoderNames = [.. PlaybackFormatCatalog.Formats.Select(format => format.EncoderName).Distinct(StringComparer.OrdinalIgnoreCase)];
}
[Fact]
public void IsTranscoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrue()
{
// Act
bool result = _sut.IsTranscoderAvailable;
// Assert
Assert.True(result);
}
[Fact]
public void IsEncoderAvailable_WhenTheStatusIsFresh_ShouldReturnTrueForEveryCatalogEncoder()
{
// Act
IReadOnlyList<bool> results = [.. _catalogEncoderNames.Select(_sut.IsEncoderAvailable)];
// Assert
Assert.All(results, result => Assert.True(result));
}
[Fact]
public void RecordUnavailable_WhenCalled_ShouldReportTheTranscoderAndEveryCatalogEncoderUnavailable()
{
// Act
_sut.RecordUnavailable();
// Assert
Assert.False(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.False(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordMissingEncoders_WhenCalled_ShouldKeepTheTranscoderAvailableAndReportOnlyTheListedEncodersUnavailable()
{
// Arrange
string missingEncoderName = _catalogEncoderNames[0];
string availableEncoderName = _catalogEncoderNames[1];
// Act
_sut.RecordMissingEncoders([missingEncoderName]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.False(_sut.IsEncoderAvailable(missingEncoderName));
Assert.True(_sut.IsEncoderAvailable(availableEncoderName));
}
[Theory]
[InlineData("AAC")] // An encoder name in upper case.
[InlineData("Aac")] // An encoder name in mixed case.
public void RecordMissingEncoders_WhenTheNameDiffersInCase_ShouldReportTheEncoderUnavailable(string missingEncoderName)
{
// Act
_sut.RecordMissingEncoders([missingEncoderName]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.False(_sut.IsEncoderAvailable("aac"));
}
[Fact]
public void RecordMissingEncoders_WhenCalledTwice_ShouldReplaceThePreviousMissingSetInsteadOfAccumulatingIt()
{
// Act
_sut.RecordMissingEncoders(["aac"]);
_sut.RecordMissingEncoders(["libopus"]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.True(_sut.IsEncoderAvailable("aac"));
Assert.False(_sut.IsEncoderAvailable("libopus"));
}
[Fact]
public void RecordMissingEncoders_WhenTheListIsEmpty_ShouldKeepEveryCatalogEncoderAvailable()
{
// Act
_sut.RecordMissingEncoders([]);
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordAvailable_WhenTheTranscoderWasUnavailable_ShouldRestoreTheTranscoderAndEveryCatalogEncoder()
{
// Arrange
_sut.RecordUnavailable();
// Act
_sut.RecordAvailable();
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.All(_catalogEncoderNames, encoderName => Assert.True(_sut.IsEncoderAvailable(encoderName)));
}
[Fact]
public void RecordAvailable_WhenEncodersWereMissing_ShouldClearTheMissingSet()
{
// Arrange
_sut.RecordMissingEncoders(["aac", "libopus"]);
// Act
_sut.RecordAvailable();
// Assert
Assert.True(_sut.IsTranscoderAvailable);
Assert.True(_sut.IsEncoderAvailable("aac"));
Assert.True(_sut.IsEncoderAvailable("libopus"));
}
}
@@ -0,0 +1,116 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Cancellation;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibrariesScanCancellationTracker"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibrariesScanCancellationTrackerTests
{
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
[Fact]
public void GetTokenForScan_WhenScanWasRegistered_ShouldReturnActiveToken()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
sut.RegisterScan(compositeId);
CancellationToken token = sut.GetTokenForScan(compositeId);
// Assert
Assert.False(token.IsCancellationRequested);
}
[Fact]
public void GetTokenForScan_WhenScanWasNotRegistered_ShouldReturnNone()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
CancellationToken token = sut.GetTokenForScan(compositeId);
// Assert
Assert.Equal(CancellationToken.None, token);
}
[Fact]
public void CancelScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
sut.RegisterScan(compositeId);
CancellationToken token = sut.GetTokenForScan(compositeId);
// Act
sut.CancelScan(compositeId);
// Assert
Assert.True(token.IsCancellationRequested);
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
}
[Fact]
public void RemoveScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
sut.RegisterScan(compositeId);
CancellationToken token = sut.GetTokenForScan(compositeId);
// Act
sut.RemoveScan(compositeId);
// Assert
Assert.True(token.IsCancellationRequested);
Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId));
}
[Fact]
public void CancelScan_WhenScanWasNotRegistered_ShouldNotThrow()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
Action act = () => sut.CancelScan(compositeId);
// Assert
act();
}
[Fact]
public void Dispose_ShouldCancelAllRegisteredScans()
{
// Arrange
MediaLibrariesScanCancellationTracker sut = new();
MediaLibraryScanCompositeId firstCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId secondCompositeId = _mediaLibraryScanCompositeIdFixture.Create();
sut.RegisterScan(firstCompositeId);
sut.RegisterScan(secondCompositeId);
CancellationToken firstToken = sut.GetTokenForScan(firstCompositeId);
CancellationToken secondToken = sut.GetTokenForScan(secondCompositeId);
// Act
sut.Dispose();
// Assert
Assert.True(firstToken.IsCancellationRequested);
Assert.True(secondToken.IsCancellationRequested);
}
}
@@ -0,0 +1,466 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicFileSystemDiscoveryJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicFileSystemDiscoveryJobTests
{
private const string ROOT_PATH = @"C:\Music";
private const string AUDIO_FILE_PATH = @"C:\Music\song.mp3";
private const string SECOND_AUDIO_FILE_PATH = @"C:\Music\other.mp3";
private const string IMAGE_FILE_PATH = @"C:\Music\cover.jpg";
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDirectoryScanFingerprintRepository _mockFingerprintRepository;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MusicFileSystemDiscoveryJob> _mockLogger;
private readonly MusicFileSystemDiscoveryJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
/// <summary>
/// Initializes a new instance of the <see cref="MusicFileSystemDiscoveryJobTests"/> class.
/// </summary>
public MusicFileSystemDiscoveryJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockFingerprintRepository = Substitute.For<IDirectoryScanFingerprintRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockFingerprintRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockServiceProvider.GetService(typeof(IFileProviderService)).Returns(_mockFileProviderService);
_mockServiceProvider.GetService(typeof(IDirectoryProviderService)).Returns(_mockDirectoryProviderService);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
// Default stubs that keep the happy path working, overridden per test where needed.
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(Result.From<long?>(0));
_mockFileProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Result.From(Optional<DateTime>.None()));
_mockDirectoryProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Result.From(Optional<DateTime>.None()));
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_mockLogger = Substitute.For<ILogger<MusicFileSystemDiscoveryJob>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new MusicFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryHasAudioFiles_ShouldStageOnlyTheAudioFilesAndComplete()
{
// Arrange
SetupLibrary();
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH)).Returns(Result.From<long?>(1234L));
_mockFileProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH))
.Returns(Result.From(Optional<DateTime>.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc))));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), true);
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), true);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
&& entities.First().Path == AUDIO_FILE_PATH
&& entities.First().Size == 1234
&& entities.First().LibraryScanId == _scanId.Value
&& entities.First().NeedsRehash),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldReadInParallelAndSkipFilesThatBecomeInaccessible()
{
// Arrange
SetupLibrary(isContentOnSsd: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH, SECOND_AUDIO_FILE_PATH, IMAGE_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == AUDIO_FILE_PATH))
.Returns(_ => throw new IOException("The file vanished between enumeration and processing"));
_mockFileProviderService.GetSize(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_AUDIO_FILE_PATH)).Returns(Result.From<long?>(1234L));
_mockFileProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == SECOND_AUDIO_FILE_PATH))
.Returns(Result.From(Optional<DateTime>.Some(new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc))));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The sequential path does not catch per-file IO exceptions, so completing here proves the parallel path was taken.
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1
&& entities.First().Path == SECOND_AUDIO_FILE_PATH
&& entities.First().Size == 1234
&& entities.First().LibraryScanId == _scanId.Value
&& entities.First().NeedsRehash),
Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Debug,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains(AUDIO_FILE_PATH, StringComparison.Ordinal)),
Arg.Any<IOException>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task ExecuteAsync_WhenHiddenFilesAndDirectoriesAreSkipped_ShouldAskTheProvidersToExcludeThem()
{
// Arrange
SetupLibrary(shouldSkipHiddenFilesAndDirectoriesDuringScan: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: [], shouldIncludeHiddenElements: false);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
_mockFileProviderService.Received(1).GetFilePaths(Arg.Any<FileSystemPathId>(), false);
_mockDirectoryProviderService.Received(1).GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), false);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheSubdirectoryHasAudioFiles_ShouldTraverseIntoIt()
{
// Arrange
const string SUBDIRECTORY_PATH = @"C:\Music\Album";
SetupLibrary();
SetupDirectory(ROOT_PATH, files: [], subdirectories: [SUBDIRECTORY_PATH]);
SetupDirectory(SUBDIRECTORY_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Path == AUDIO_FILE_PATH),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryIsUnchanged_ShouldSkipIt()
{
// Arrange
DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
_mockDirectoryProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == ROOT_PATH))
.Returns(Result.From(Optional<DateTime>.Some(lastWriteTime)));
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
{
[ROOT_PATH] = _directoryScanFingerprintEntityFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime)
}));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFastSkipIsEnabledAndTheDirectoryChanged_ShouldStoreAFingerprint()
{
// Arrange
DateTime lastWriteTime = new(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
_mockDirectoryProviderService.GetLastWriteTime(Arg.Is<FileSystemPathId>(path => path.Path == ROOT_PATH))
.Returns(Result.From(Optional<DateTime>.Some(lastWriteTime)));
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>
{
[ROOT_PATH] = _directoryScanFingerprintEntityFixture.Create(libraryId: _libraryId.Value, path: ROOT_PATH, lastWriteTimeUtc: lastWriteTime.AddDays(-1))
}));
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFingerprintRepository.Received(1).UpsertRangeAsync(
Arg.Is<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(fingerprints => fingerprints.Count == 1 && fingerprints.First().Path == ROOT_PATH),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFileSizeAndLastWriteTimeCannotBeRead_ShouldStageTheFileWithDefaults()
{
// Arrange
SetupLibrary();
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(Error.Failure("FileSystem.Error", "Failed to read the size"));
_mockFileProviderService.GetLastWriteTime(Arg.Any<FileSystemPathId>()).Returns(Error.Failure("FileSystem.Error", "Failed to read the last write time"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && entities.First().Size == 0 && entities.First().Ticks == 0),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenReadingTheDirectoryFails_ShouldSkipItAndComplete()
{
// Arrange
SetupLibrary();
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the files"));
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Any<FileSystemPathId>(), true).Returns(Error.Failure("FileSystem.Error", "Failed to read the subdirectories"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed()
{
// Arrange
SetupLibrary();
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to stage the discovered files"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenAFileMetadataReadThrowsAnUnexpectedException_ShouldMarkJobAsFailed()
{
// Arrange
SetupLibrary(isContentOnSsd: true);
SetupDirectory(ROOT_PATH, files: [AUDIO_FILE_PATH], subdirectories: []);
_mockFileProviderService.GetSize(Arg.Any<FileSystemPathId>()).Returns(_ => throw new InvalidOperationException("Unexpected defect"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheFingerprintUpsertFails_ShouldMarkJobAsFailed()
{
// Arrange
SetupLibrary(shouldSkipUnchangedDirectoriesDuringScan: true);
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
_mockFingerprintRepository.GetMappedByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Dictionary<string, DirectoryScanFingerprintEntity>()));
_mockFingerprintRepository.UpsertRangeAsync(Arg.Any<IReadOnlyCollection<DirectoryScanFingerprintEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to store the fingerprints"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren()
{
// Arrange
SetupLibrary();
SetupDirectory(ROOT_PATH, files: [], subdirectories: []);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Stubs the media library reader with a library whose single content location is the test root path.
/// </summary>
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether the library skips the directories that have not changed since the last scan.</param>
/// <param name="shouldSkipHiddenFilesAndDirectoriesDuringScan">Whether the library skips hidden files and directories.</param>
/// <param name="isContentOnSsd">Whether the content of the library is stored on a solid state drive.</param>
private void SetupLibrary(bool shouldSkipUnchangedDirectoriesDuringScan = false, bool shouldSkipHiddenFilesAndDirectoriesDuringScan = false, bool isContentOnSsd = false)
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [ROOT_PATH],
shouldSkipUnchangedDirectoriesDuringScan: shouldSkipUnchangedDirectoriesDuringScan,
shouldSkipHiddenFilesAndDirectoriesDuringScan: shouldSkipHiddenFilesAndDirectoriesDuringScan,
isContentOnSsd: isContentOnSsd);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
/// <summary>
/// Stubs the file and directory providers for the provided directory.
/// </summary>
/// <param name="directory">The file system path of the directory.</param>
/// <param name="files">The file system paths of the files of the directory.</param>
/// <param name="subdirectories">The file system paths of the subdirectories of the directory.</param>
/// <param name="shouldIncludeHiddenElements">Whether the providers are expected to include hidden elements.</param>
private void SetupDirectory(string directory, string[] files, string[] subdirectories, bool shouldIncludeHiddenElements = true)
{
_mockFileProviderService.GetFilePaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. files.Select(file => PathId(file))]));
_mockDirectoryProviderService.GetSubdirectoryPaths(Arg.Is<FileSystemPathId>(path => path.Path == directory), shouldIncludeHiddenElements)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([.. subdirectories.Select(subdirectoryPath => PathId(subdirectoryPath))]));
}
/// <summary>
/// Creates a file system path id for the provided path.
/// </summary>
/// <param name="path">The path to create the id for.</param>
/// <returns>The created file system path id.</returns>
private static FileSystemPathId PathId(string path)
{
return FileSystemPathId.Create(path).Value;
}
}
@@ -0,0 +1,195 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryPathStructure"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathStructureTests
{
private readonly IPathService _mockPathService;
private readonly MusicLibraryPathStructure _sut;
/// <summary>
/// Initializes a new instance of the <see cref="MusicLibraryPathStructureTests"/> class.
/// </summary>
public MusicLibraryPathStructureTests()
{
_mockPathService = Substitute.For<IPathService>();
_sut = new MusicLibraryPathStructure(_mockPathService);
}
[Theory]
[InlineData('\\', @"C:\Music\Queen\A Night at the Opera", @"C:\Music\Queen\A Night at the Opera\Bohemian Rhapsody.flac")] // Windows separated path.
[InlineData('/', "/music/queen/a-night-at-the-opera", "/music/queen/a-night-at-the-opera/bohemian-rhapsody.flac")] // Unix separated path.
public void GetAlbumDirectory_WhenTheTrackIsInTheAlbumDirectory_ShouldReturnTheTrackDirectory(char separator, string albumDirectory, string trackPath)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
// Act
string result = _sut.GetAlbumDirectory(trackPath);
// Assert
Assert.Equal(albumDirectory, result);
}
[Theory]
[InlineData('\\', "Disc 1")] // Canonical disc directory name, Windows separated path.
[InlineData('\\', "disc 2")] // Lowercase disc directory name, Windows separated path.
[InlineData('\\', "CD3")] // Compact disc directory name, Windows separated path.
[InlineData('\\', "disk4")] // Disk directory name, Windows separated path.
[InlineData('/', "Disc 1")] // Canonical disc directory name, Unix separated path.
[InlineData('/', "disc 2")] // Lowercase disc directory name, Unix separated path.
[InlineData('/', "CD3")] // Compact disc directory name, Unix separated path.
[InlineData('/', "disk4")] // Disk directory name, Unix separated path.
public void GetAlbumDirectory_WhenTheTrackIsInADiscDirectory_ShouldReturnTheParentAlbumDirectory(char separator, string discDirectoryName)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string albumDirectory = string.Join(separator, "music", "queen", "a-night-at-the-opera");
string trackPath = string.Join(separator, albumDirectory, discDirectoryName, "bohemian-rhapsody.flac");
// Act
string result = _sut.GetAlbumDirectory(trackPath);
// Assert
Assert.Equal(albumDirectory, result);
}
[Theory]
[InlineData('\\')] // Windows separated path.
[InlineData('/')] // Unix separated path.
public void GetAlbumDirectory_WhenTheDirectoryIsNotADiscDirectory_ShouldReturnTheTrackDirectory(char separator)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string albumDirectory = string.Join(separator, "music", "queen", "live");
string trackPath = string.Join(separator, albumDirectory, "bohemian-rhapsody.flac");
// Act
string result = _sut.GetAlbumDirectory(trackPath);
// Assert
Assert.Equal(albumDirectory, result);
}
[Fact]
public void GetAlbumDirectory_WhenThePathIsNullOrEmpty_ShouldReturnTheProvidedPath()
{
// Act
string nullResult = _sut.GetAlbumDirectory(null!);
string emptyResult = _sut.GetAlbumDirectory(string.Empty);
// Assert
Assert.Null(nullResult);
Assert.Equal(string.Empty, emptyResult);
}
[Theory]
[InlineData('\\')] // Windows separated path.
[InlineData('/')] // Unix separated path.
public void GetAlbumDirectory_WhenThePathHasNoDirectory_ShouldReturnTheProvidedPath(char separator)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
const string FILE_NAME_ONLY = "Bohemian Rhapsody.flac";
// Act
string result = _sut.GetAlbumDirectory(FILE_NAME_ONLY);
// Assert
Assert.Equal(FILE_NAME_ONLY, result);
}
[Theory]
[InlineData('\\', "Album")] // Canonical release type directory, Windows separated path.
[InlineData('\\', "album")] // Lowercase release type directory, Windows separated path.
[InlineData('/', "Album")] // Canonical release type directory, Unix separated path.
[InlineData('/', "album")] // Lowercase release type directory, Unix separated path.
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsAReleaseType_ShouldReturnIt(char separator, string releaseTypeDirectoryName)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string trackPath = string.Join(separator, "music", "queen", releaseTypeDirectoryName, "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
// Assert
Assert.Equal(releaseTypeDirectoryName, result);
}
[Theory]
[InlineData('\\')] // Windows separated path.
[InlineData('/')] // Unix separated path.
public void GetReleaseTypeDirectoryName_WhenTheAlbumIsMultiDisc_ShouldReturnTheReleaseTypeDirectory(char separator)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string trackPath = string.Join(separator, "music", "queen", "Album", "a-night-at-the-opera", "Disc 1", "bohemian-rhapsody.flac");
// Act
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
// Assert
Assert.Equal("Album", result);
}
[Theory]
[InlineData('\\')] // Windows separated path.
[InlineData('/')] // Unix separated path.
public void GetReleaseTypeDirectoryName_WhenTheParentOfTheAlbumDirectoryIsNotAReleaseType_ShouldReturnNull(char separator)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string trackPath = string.Join(separator, "music", "queen", "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
string? result = _sut.GetReleaseTypeDirectoryName(trackPath);
// Assert
Assert.Null(result);
}
[Theory]
[InlineData('\\', "Live")] // Release type name used as the artist directory name, Windows separated path.
[InlineData('/', "Live")] // Release type name used as the artist directory name, Unix separated path.
[InlineData('\\', "42")] // Numeric artist directory name, Windows separated path.
[InlineData('/', "42")] // Numeric artist directory name, Unix separated path.
public void GetReleaseTypeDirectoryName_WhenTheArtistDirectoryIsNamedLikeAReleaseType_ShouldReturnNull(char separator, string artistName)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
// The library uses no release type directory, so the parent of the album directory is the artist directory.
string trackPath = string.Join(separator, "music", artistName, "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
string? result = _sut.GetReleaseTypeDirectoryName(trackPath, artistName);
// Assert
Assert.Null(result);
}
[Theory]
[InlineData('\\')] // Windows separated path.
[InlineData('/')] // Unix separated path.
public void GetReleaseTypeDirectoryName_WhenAReleaseTypeDirectoryDiffersFromTheArtistDirectory_ShouldReturnIt(char separator)
{
// Arrange
_mockPathService.PathSeparator.Returns(separator);
string trackPath = string.Join(separator, "music", "Queen", "Live", "a-night-at-the-opera", "bohemian-rhapsody.flac");
// Act
string? result = _sut.GetReleaseTypeDirectoryName(trackPath, "Queen");
// Assert
Assert.Equal("Live", result);
}
}
@@ -0,0 +1,619 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Artwork;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
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.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicMediaLibraryScanArtworkEnricher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMediaLibraryScanArtworkEnricherTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly IMusicArtworkRepository _mockMusicArtworkRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IMusicArtworkService _mockMusicArtworkService;
private readonly IFileHashService _mockFileHashService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly IPathService _mockPathService;
private readonly TestArtworkProvider<ArtistMetadataLookupDto> _artistProvider;
private readonly TestArtworkProvider<AlbumMetadataLookupDto> _albumProvider;
private readonly MusicMediaLibraryScanArtworkEnricher _sut;
private readonly ServiceProvider _serviceProvider;
private readonly Guid _artistPluginId = Guid.NewGuid();
private readonly Guid _albumPluginId = Guid.NewGuid();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanArtworkEnricherTests"/> class.
/// </summary>
public MusicMediaLibraryScanArtworkEnricherTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockMusicArtworkRepository = Substitute.For<IMusicArtworkRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.MusicArtworkRepository.Returns(_mockMusicArtworkRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_artistProvider = new TestArtworkProvider<ArtistMetadataLookupDto> { Name = "Artist Provider", RequiresWebAccess = false };
_albumProvider = new TestArtworkProvider<AlbumMetadataLookupDto> { Name = "Album Provider", RequiresWebAccess = false };
_mockMusicArtworkService = Substitute.For<IMusicArtworkService>();
_mockFileHashService = Substitute.For<IFileHashService>();
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('/');
// The enricher resolves the keyed artwork providers from the scope of the service provider, and specializes them by the lookup they accept,
// so a real container is used to honor the keyed registration of the typed providers.
ServiceCollection services = new();
services.AddScoped<IUnitOfWork>(_ => _mockUnitOfWork);
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
services.AddSingleton(_mockMusicArtworkService);
services.AddSingleton(_mockFileHashService);
services.AddKeyedSingleton<IArtworkProvider>(_artistPluginId, _artistProvider);
services.AddKeyedSingleton<IArtworkProvider>(_albumPluginId, _albumProvider);
_serviceProvider = services.BuildServiceProvider();
_sut = new MusicMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanArtworkEnricher>.Instance, new MusicLibraryPathStructure(_mockPathService));
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
// Default stubs that keep the happy path working, overridden per test where needed.
SetupLibrary();
SetupConfiguration();
_mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result<UserSettingsEntity?>.Success(null));
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<ArtistEntity>>([]));
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(0));
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([]));
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(new Dictionary<Guid, string>()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
SetupSuccessArtworkStorage();
}
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Music, result);
}
[Fact]
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
{
// Arrange
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
{
// Arrange
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
{
// Arrange
SetupLibrary(canDownloadMetadataFromWeb: false);
_artistProvider.RequiresWebAccess = true;
_albumProvider.RequiresWebAccess = true;
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockArtistRepository.DidNotReceive().GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockAlbumRepository.DidNotReceive().GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
{
// Arrange
SetupLibrary(canDownloadMetadataFromWeb: false);
_artistProvider.RequiresWebAccess = true;
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
SetupAlbums(album);
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
Assert.Equal(1, _albumProvider.CallCount);
Assert.Equal(0, _artistProvider.CallCount);
}
[Fact]
public async Task EnrichAsync_WhenTheArtistProviderReturnsArtwork_ShouldStoreAndPersistEnrichedArtistArtwork()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkService.Received(1).SaveArtistArtworkAsync(
_libraryId.Value,
Arg.Any<string>(),
artist.Id,
artist.Name,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
&& entities.First().OwnerId == artist.Id
&& entities.First().ArtworkType == ArtworkType.Cover
&& entities.First().Ordinal == 0
&& entities.First().Status == ArtworkStatus.Enriched
&& entities.First().Provider == "Artist Provider"
&& entities.First().FileName == "/media/music/cover.jpg"
&& entities.First().ContentHash == 123UL),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheAlbumProviderReturnsArtwork_ShouldStoreAndPersistEnrichedAlbumArtwork()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
SetupAlbums(album);
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkService.Received(1).SaveAlbumArtworkAsync(
_libraryId.Value,
album.Id,
Arg.Any<string>(),
album.ArtistId,
Arg.Any<string>(),
album.Title,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Album, album.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
&& entities.First().OwnerType == MusicArtworkOwnerType.Album
&& entities.First().OwnerId == album.Id
&& entities.First().Status == ArtworkStatus.Enriched
&& entities.First().Provider == "Album Provider"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheProviderAnswersWithNoArtwork_ShouldMarkTheArtistNotAvailable()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
&& entities.First().Status == ArtworkStatus.NotAvailable
&& entities.First().FileName == null
&& entities.First().Provider == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheArtistFailed()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure."));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheArtistFailed()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1 && entities.First().Status == ArtworkStatus.Failed),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenClearingTheStoredArtworkFilesFails_ShouldClearTheStoredArtworkRecordsAndMarkTheArtistFailed()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>())
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork files"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.Received(1).DeleteByOwnerAsync(MusicArtworkOwnerType.Artist, artist.Id, Arg.Any<CancellationToken>());
await _mockMusicArtworkRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicArtworkEntity>>(entities => entities.Count == 1
&& entities.First().OwnerType == MusicArtworkOwnerType.Artist
&& entities.First().OwnerId == artist.Id
&& entities.First().Status == ArtworkStatus.Failed
&& entities.First().FileName == null),
Arg.Any<CancellationToken>());
await _mockMusicArtworkService.DidNotReceive().SaveArtistArtworkAsync(
Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenClearingTheStoredArtworkRecordsFails_ShouldLeaveTheArtistUnresolved()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Artwork.Error", "Failed to clear the artwork records"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheAlbumHasNoMusicBrainzIdentifierAndNoLocalProvider_ShouldLeaveItUnresolved()
{
// Arrange
_albumProvider.RequiresWebAccess = true;
AlbumEntity album = _albumEntityFixture.Create(
libraryId: _libraryId.Value,
includeMusicBrainzReleaseId: false,
includeMusicBrainzReleaseGroupId: false);
SetupAlbums(album);
_albumProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
Assert.Equal(0, _albumProvider.CallCount);
await _mockMusicArtworkRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheAlbumCountCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to count the albums"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheAlbumsPageCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to read the albums"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheTrackPathsCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
AlbumEntity album = _albumEntityFixture.Create(libraryId: _libraryId.Value);
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<AlbumEntity>>([album]));
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to read the track paths"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
SetupArtists(artist);
_artistProvider.OnGetArtworkAsync = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/tmp/cover.jpg", remoteUrl: null)]);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
/// <summary>
/// Stubs the media library reader with a library owned by the test user.
/// </summary>
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
/// <summary>
/// Stubs the artwork provider configuration reader with one enabled configuration per test plugin.
/// </summary>
private void SetupConfiguration()
{
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
[
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _artistPluginId, 0),
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _albumPluginId, 1)
]));
}
/// <summary>
/// Stubs the artist reader with a single page holding the provided artists.
/// </summary>
/// <param name="artists">The artists of the page.</param>
private void SetupArtists(params ArtistEntity[] artists)
{
_mockArtistRepository.GetArtistsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(artists.Length));
_mockArtistRepository.GetArtistsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<ArtistEntity>>(artists),
Result.From<IReadOnlyList<ArtistEntity>>([]));
}
/// <summary>
/// Stubs the album reader with a single page holding the provided albums.
/// </summary>
/// <param name="albums">The albums of the page.</param>
private void SetupAlbums(params AlbumEntity[] albums)
{
_mockAlbumRepository.GetAlbumsNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(albums.Length));
_mockAlbumRepository.GetAlbumsNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<AlbumEntity>>(albums),
Result.From<IReadOnlyList<AlbumEntity>>([]));
Dictionary<Guid, string> trackPaths = albums.ToDictionary(album => album.Id, album => "/music/artist/album/track.flac");
_mockAlbumRepository.GetFirstTrackPathsByAlbumIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string>>(trackPaths));
}
/// <summary>
/// Stubs the artwork storage and persistence so that an item is stored successfully.
/// </summary>
private void SetupSuccessArtworkStorage()
{
_mockMusicArtworkService.SaveArtistArtworkAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.SaveAlbumArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From("/media/music/cover.jpg"));
_mockMusicArtworkService.DeleteArtistArtwork(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>()).Returns(Result.Deleted);
_mockMusicArtworkService.DeleteAlbumArtwork(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>()).Returns(Result.Deleted);
_mockMusicArtworkRepository.DeleteByOwnerAsync(Arg.Any<MusicArtworkOwnerType>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_mockMusicArtworkRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicArtworkEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
}
/// <summary>
/// Deterministic artwork provider for a specific lookup type, used instead of a substitute because the default implementation of
/// <see cref="IArtworkProvider.GetArtworkAsync(MetadataLookupDto, CancellationToken)"/> cannot be intercepted reliably.
/// </summary>
/// <typeparam name="TLookup">The type of the lookup the provider accepts.</typeparam>
private sealed class TestArtworkProvider<TLookup> : IArtworkProvider<TLookup> where TLookup : MetadataLookupDto
{
/// <summary>
/// Gets or sets the display name of the artwork provider.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the media library types this artwork provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes { get; set; } = [LibraryType.Music];
/// <summary>
/// Gets or sets a value indicating whether this artwork provider requires access to the web to retrieve artwork.
/// </summary>
public bool RequiresWebAccess { get; set; }
/// <summary>
/// Gets or sets the callback that supplies the artwork of a media item.
/// </summary>
public Func<TLookup, CancellationToken, Task<IReadOnlyList<ArtworkDto>>> OnGetArtworkAsync { get; set; } = (_, _) => Task.FromResult<IReadOnlyList<ArtworkDto>>([]);
/// <summary>
/// Gets the number of times the provider was asked for artwork.
/// </summary>
public int CallCount { get; private set; }
/// <summary>
/// Gets the artworks of the media item described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the media item to get the artwork for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artworks of the media item, or an empty collection when no artwork was found.</returns>
public Task<IReadOnlyList<ArtworkDto>> GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken)
{
CallCount++;
return OnGetArtworkAsync(lookup, cancellationToken);
}
}
}
@@ -0,0 +1,272 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicMediaLibraryScanItemMaterializer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMediaLibraryScanItemMaterializerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ITrackRepository _mockTrackRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockStagedMetadataRepository;
private readonly IPathService _mockPathService;
private readonly MusicMediaLibraryScanItemMaterializer _sut;
private readonly MusicLibraryScanItemMetadataEntityFixture _musicLibraryScanItemMetadataEntityFixture = new();
private readonly List<ArtistEntity> _insertedArtists = [];
private readonly Guid _libraryId = Guid.NewGuid();
private readonly Guid _scanId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanItemMaterializerTests"/> class.
/// </summary>
public MusicMediaLibraryScanItemMaterializerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockStagedMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockStagedMetadataRepository);
_mockArtistRepository.GetByNameAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From<ArtistEntity?>(null));
_mockAlbumRepository.GetByTitleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Result.From<AlbumEntity?>(null));
_mockArtistRepository.InsertAsync(Arg.Do<ArtistEntity>(artist => _insertedArtists.Add(artist)), Arg.Any<CancellationToken>())
.Returns(Result.From(new Created()));
_mockAlbumRepository.InsertAsync(Arg.Any<AlbumEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Created()));
_mockTrackRepository.InsertAsync(Arg.Any<TrackEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(new Created()));
_mockTrackRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockStagedMetadataRepository.DeleteByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockStagedMetadataRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([]));
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('/');
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
_sut = new MusicMediaLibraryScanItemMaterializer(new MusicLibraryPathStructure(_mockPathService), _mockPathService);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheTracksLiveInDifferentDirectories_ShouldMaterializeOneAlbumPerDirectory()
{
// Arrange
Guid releaseArtistId = Guid.NewGuid();
Guid firstReleaseId = Guid.NewGuid();
Guid secondReleaseId = Guid.NewGuid();
Guid firstRecordingId = Guid.NewGuid();
Guid secondRecordingId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Shared Artist Name",
releaseName: "Shared Release Title",
path: "/music/shared-artist/release-one/first.mp3",
musicBrainzArtistId: Guid.NewGuid(),
musicBrainzReleaseArtistId: releaseArtistId,
musicBrainzReleaseId: firstReleaseId,
musicBrainzRecordingId: firstRecordingId);
MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Shared Artist Name",
releaseName: "Shared Release Title",
path: "/music/shared-artist/release-two/second.mp3",
musicBrainzArtistId: Guid.NewGuid(),
musicBrainzReleaseArtistId: releaseArtistId,
musicBrainzReleaseId: secondReleaseId,
musicBrainzRecordingId: secondRecordingId);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
// The same artist name groups the items under a single artist, whose identifier is the one of the release artist.
ArtistEntity artist = Assert.Single(_insertedArtists);
Assert.Equal(releaseArtistId, artist.MusicBrainzArtistId);
// The distinct release identifiers keep the identically titled releases apart.
Assert.Equal(2, artist.Albums.Count);
AlbumEntity firstAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == firstReleaseId);
AlbumEntity secondAlbum = artist.Albums.Single(album => album.MusicBrainzReleaseId == secondReleaseId);
Assert.Equal(firstRecordingId, Assert.Single(firstAlbum.Tracks).MusicBrainzRecordingId);
Assert.Equal(secondRecordingId, Assert.Single(secondAlbum.Tracks).MusicBrainzRecordingId);
// The container read from the file itself is carried from the staged metadata to the materialized track.
Assert.Equal(firstStagedItem.Container, Assert.Single(firstAlbum.Tracks).Container);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheStagedItemHasNoContainer_ShouldMaterializeTheTrackWithoutAContainer()
{
// Arrange
MusicLibraryScanItemMetadataEntity stagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Some Artist",
releaseName: "Some Release",
path: "/music/some-artist/some-release/track.mp3",
includeMusicBrainzTags: false,
includeContainer: false);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
ArtistEntity artist = Assert.Single(_insertedArtists);
AlbumEntity album = Assert.Single(artist.Albums);
// A file whose container the scan could not recognize materializes its track without a container, rather than failing the scan.
Assert.Null(Assert.Single(album.Tracks).Container);
}
[Fact]
public async Task MaterializeItemsAsync_WhenCompilationTracksHaveDifferentTrackArtists_ShouldMaterializeASingleAlbumArtist()
{
// Arrange
Guid variousArtistsId = Guid.NewGuid();
Guid compilationReleaseId = Guid.NewGuid();
MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Various Artists",
releaseName: "Now That Is Music",
path: "/music/various-artists/now-that-is-music/first.mp3",
musicBrainzArtistId: Guid.NewGuid(),
musicBrainzReleaseArtistId: variousArtistsId,
musicBrainzReleaseId: compilationReleaseId);
MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Various Artists",
releaseName: "Now That Is Music",
path: "/music/various-artists/now-that-is-music/second.mp3",
musicBrainzArtistId: Guid.NewGuid(),
musicBrainzReleaseArtistId: variousArtistsId,
musicBrainzReleaseId: compilationReleaseId);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
// The different track artists of the compilation do not split the release artist into several identically named artists.
ArtistEntity artist = Assert.Single(_insertedArtists);
Assert.Equal("Various Artists", artist.Name);
Assert.Equal(variousArtistsId, artist.MusicBrainzArtistId);
AlbumEntity album = Assert.Single(artist.Albums);
Assert.Equal(2, album.Tracks.Count);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheTagsDoNotCarryMusicBrainzIds_ShouldGroupByTheNameAndTitle()
{
// Arrange
MusicLibraryScanItemMetadataEntity firstStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Shared Artist Name",
releaseName: "Shared Release Title",
path: "/music/shared-artist/shared-release/first.mp3",
includeMusicBrainzTags: false);
MusicLibraryScanItemMetadataEntity secondStagedItem = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Shared Artist Name",
releaseName: "Shared Release Title",
path: "/music/shared-artist/shared-release/second.mp3",
includeMusicBrainzTags: false);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([firstStagedItem, secondStagedItem]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(firstStagedItem.Path, secondStagedItem.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
// Without identifiers, the items fall back to the name and the title, so they collapse into a single artist with a single album.
ArtistEntity artist = Assert.Single(_insertedArtists);
AlbumEntity album = Assert.Single(artist.Albums);
Assert.Null(artist.MusicBrainzArtistId);
Assert.Null(album.MusicBrainzReleaseId);
Assert.Equal(2, album.Tracks.Count);
}
[Fact]
public async Task MaterializeItemsAsync_WhenTheCurrentScanStagedNothing_ShouldMaterializeTheMetadataLeftBehindByAnEarlierScanForTheCurrentSnapshotPaths()
{
// Arrange
MusicLibraryScanItemMetadataEntity stagedItemInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Recovered Artist",
releaseName: "Recovered Release",
path: "/music/recovered-artist/recovered-release/first.mp3",
includeMusicBrainzTags: false);
MusicLibraryScanItemMetadataEntity stagedItemNoLongerInSnapshot = _musicLibraryScanItemMetadataEntityFixture.Create(
libraryId: _libraryId,
artistName: "Deleted Artist",
releaseName: "Deleted Release",
path: "/music/deleted-artist/deleted-release/deleted.mp3",
includeMusicBrainzTags: false);
_mockStagedMetadataRepository.GetByLibraryIdAsync(_libraryId, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<MusicLibraryScanItemMetadataEntity>>([stagedItemInSnapshot, stagedItemNoLongerInSnapshot]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet(stagedItemInSnapshot.Path), CancellationToken.None);
// Assert
Assert.True(result.IsSuccess);
// The metadata left behind by the earlier scan is reused only for the files that are still in the current snapshot.
ArtistEntity artist = Assert.Single(_insertedArtists);
Assert.Equal("Recovered Artist", artist.Name);
AlbumEntity album = Assert.Single(artist.Albums);
Assert.Equal(stagedItemInSnapshot.Path, Assert.Single(album.Tracks).Path);
}
[Fact]
public async Task ClearStagedDataAsync_WhenCalled_ShouldDeleteTheStagedMetadataOfTheWholeLibrary()
{
// Act
Result<Deleted> result = await _sut.ClearStagedDataAsync(_mockUnitOfWork, _libraryId, _scanId, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Deleted, result.Value);
await _mockStagedMetadataRepository.Received(1).DeleteByLibraryIdAsync(_libraryId, CancellationToken.None);
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the media library scan produces.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}
@@ -0,0 +1,326 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
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.AudioLibrary.MusicLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicMediaLibraryScanMetadataEnricher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMediaLibraryScanMetadataEnricherTests
{
private const string PROVIDER_A_NAME = "ProviderA";
private const string PROVIDER_B_NAME = "ProviderB";
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IArtistRepository _mockArtistRepository;
private readonly IAlbumRepository _mockAlbumRepository;
private readonly ITrackRepository _mockTrackRepository;
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IMetadataProvider _mockProviderA;
private readonly IMetadataProvider _mockProviderB;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ServiceProvider _serviceProvider;
private readonly MusicMediaLibraryScanMetadataEnricher _sut;
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly ArtistMetadataDtoFixture _artistMetadataDtoFixture = new();
private readonly GenreDtoFixture _genreDtoFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMediaLibraryScanMetadataEnricherTests"/> class.
/// </summary>
public MusicMediaLibraryScanMetadataEnricherTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockArtistRepository = Substitute.For<IArtistRepository>();
_mockAlbumRepository = Substitute.For<IAlbumRepository>();
_mockTrackRepository = Substitute.For<ITrackRepository>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockUnitOfWork.ArtistRepository.Returns(_mockArtistRepository);
_mockUnitOfWork.AlbumRepository.Returns(_mockAlbumRepository);
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(Substitute.For<IMediaContributorRepository>());
// Both plugins expose only an artist metadata provider, so that the tests exercise the artist lookup in isolation, without album or track lookups ever reaching a provider.
_mockProviderA = Substitute.For<IMetadataProvider>();
ConfigureProvider(_mockProviderA, PROVIDER_A_NAME);
_mockProviderB = Substitute.For<IMetadataProvider>();
ConfigureProvider(_mockProviderB, PROVIDER_B_NAME);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
// The configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services.
Guid pluginAId = Guid.NewGuid();
Guid pluginBId = Guid.NewGuid();
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>.Success(
[
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1),
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2)
]));
ServiceCollection services = new();
services.AddScoped<IUnitOfWork>(_ => _mockUnitOfWork);
services.AddScoped<IDomainEventPublisher>(_ => _mockDomainEventPublisher);
services.AddKeyedTransient<IMetadataProvider>(pluginAId, (serviceProvider, serviceKey) => _mockProviderA);
services.AddKeyedTransient<IMetadataProvider>(pluginBId, (serviceProvider, serviceKey) => _mockProviderB);
_serviceProvider = services.BuildServiceProvider();
_sut = new MusicMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<MusicMediaLibraryScanMetadataEnricher>.Instance);
_mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(1));
_mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(1));
_mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(1));
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([]));
_mockArtistRepository.UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
}
[Fact]
public async Task EnrichAsync_WhenArtistsAlbumsAndTracksNeedEnrichment_ShouldPublishProgressMeasuredInItems()
{
// Arrange
_mockArtistRepository.GetArtistsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(2));
_mockAlbumRepository.GetAlbumsNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(3));
_mockTrackRepository.GetTracksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(5));
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
// The total is the sum of the artists, the albums and the tracks, and the final update reaches it.
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent =>
domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.Progress.CompletedItems == 0
&& domainEvent.Progress.TotalItems == 10), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent =>
domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.Progress.CompletedItems == 10
&& domainEvent.Progress.TotalItems == 10), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_A_NAME),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)null);
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheMetadataOfTheFirstProviderCannotBeApplied_ShouldQueryTheFollowingProviders()
{
// Arrange
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
// A genre without a name is usable as metadata, but makes the domain conversion of the whole metadata fail.
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist", genres: [_genreDtoFixture.Create(includeName: false)]));
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == PROVIDER_B_NAME),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenSavingFailsWithAUniqueConstraintViolation_ShouldContinueWithTheFollowingArtists()
{
// Arrange
ArtistEntity firstArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "First Artist");
ArtistEntity secondArtist = _artistEntityFixture.Create(libraryId: _libraryId.Value, name: "Second Artist");
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([firstArtist, secondArtist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result<Success>.Failure(Errors.Persistence.UniqueConstraintViolation), Result.From(Result.Success));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
// The first artist's save fails with a unique constraint conflict, which must not abort the scan, so the second artist is still processed.
await _mockUnitOfWork.Received(2).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(2).UpdateAsync(Arg.Any<ArtistEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata()
{
// Arrange
_mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any<CancellationToken>())
.Returns(Result<UserSettingsEntity?>.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true)));
ArtistEntity artist = _artistEntityFixture.Create(libraryId: _libraryId.Value);
_mockArtistRepository.GetArtistsNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<ArtistEntity>>.Success([artist]), Result<IReadOnlyList<ArtistEntity>>.Success([]));
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Local Artist"));
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableArtistMetadata("Remote Artist"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockArtistRepository.Received(1).UpdateAsync(
Arg.Is<ArtistEntity>(entity => entity.MetadataStatus == MetadataStatus.Enriched && entity.MetadataProvider == $"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}"),
Arg.Any<CancellationToken>());
}
/// <summary>
/// Configures the provided substitute metadata provider so that it declares the artist lookup type for the music library type.
/// </summary>
/// <param name="metadataProvider">The metadata provider substitute to configure.</param>
/// <param name="name">The display name the provider reports.</param>
private static void ConfigureProvider(IMetadataProvider metadataProvider, string name)
{
metadataProvider.Name.Returns(name);
metadataProvider.SupportedLibraryTypes.Returns(new List<LibraryType> { LibraryType.Music });
metadataProvider.RequiresWebAccess.Returns(false);
metadataProvider.LookupType.Returns(typeof(ArtistMetadataLookupDto));
}
/// <summary>
/// Creates an artist metadata that is usable and carries only a name, and optionally a set of genres.
/// </summary>
/// <param name="name">The name of the artist.</param>
/// <param name="genres">The optional genres of the artist.</param>
/// <returns>The created artist metadata.</returns>
private ArtistMetadataDto CreateApplicableArtistMetadata(string name, List<GenreDto>? genres = null)
{
return _artistMetadataDtoFixture.Create(
name: name,
genres: genres,
includeSortName: false,
includeDisambiguation: false,
includeType: false,
includeGender: false,
includeCountry: false,
includeArea: false,
includeBeginArea: false,
includeEndArea: false,
includeLifeSpanBegin: false,
includeLifeSpanEnd: false,
includeWebsite: false,
includeMusicBrainzArtistId: false,
includeIpis: false,
includeIsnis: false,
includeGenres: genres is not null,
includeTags: false,
includeAliases: false,
includeRatings: false,
includeContributors: false);
}
}
@@ -0,0 +1,279 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Audio.Music;
/// <summary>
/// Contains unit tests for the <see cref="MusicMetadataExtractionJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicMetadataExtractionJobTests
{
private const string ROOT_PATH = @"C:\Music";
private const string AUDIO_FILE_PATH = @"C:\Music\Queen\Bohemian Rhapsody.mp3";
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMusicLibraryScanItemMetadataRepository _mockMusicMetadataRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly ILibraryPathTemplateService _mockPathTemplateService;
private readonly IPathService _mockPathService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MusicMetadataExtractionJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
/// <summary>
/// Initializes a new instance of the <see cref="MusicMetadataExtractionJobTests"/> class.
/// </summary>
public MusicMetadataExtractionJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMusicMetadataRepository = Substitute.For<IMusicLibraryScanItemMetadataRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.MusicLibraryScanItemMetadataRepository.Returns(_mockMusicMetadataRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockServiceProvider.GetService(typeof(ILibraryPathTemplateService)).Returns(_mockPathTemplateService);
_mockServiceProvider.GetService(typeof(IPathService)).Returns(_mockPathService);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
// Default stubs that keep the happy path working, overridden per test where needed.
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(_libraryPathTemplateFixture.Create()));
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>()).Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.None()));
_mockPathService.IsPathWithin(Arg.Any<string>(), Arg.Any<string>()).Returns(true);
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_sut = new MusicMetadataExtractionJob(_mockServiceScopeFactory, Substitute.For<Microsoft.Extensions.Logging.ILogger<MusicMetadataExtractionJob>>())
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockMusicMetadataRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenThereArePathsToProcess_ShouldStageTheirMetadataAndComplete()
{
// Arrange
SetupLibrary();
SetupPaths(AUDIO_FILE_PATH);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().Path == AUDIO_FILE_PATH
&& items.First().LibraryScanId == _scanId.Value
&& items.First().LibraryId == _libraryId.Value
&& items.First().TrackTitle == "Bohemian Rhapsody"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenThePathMatchesTheTemplate_ShouldApplyThePathDerivedMetadata()
{
// Arrange
SetupLibrary();
SetupPaths(AUDIO_FILE_PATH);
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen",
[LibraryPathPartKind.ReleaseType] = "Album",
[LibraryPathPartKind.ReleaseYear] = "1975",
[LibraryPathPartKind.ReleaseName] = "A Night at the Opera",
[LibraryPathPartKind.TrackNumber] = "11",
[LibraryPathPartKind.DiscNumber] = "1",
[LibraryPathPartKind.TrackName] = "Bohemian Rhapsody"
});
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>())
.Returns(Result.From<Optional<ParsedLibraryPath>>(Optional<ParsedLibraryPath>.Some(parsedPath)));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockMusicMetadataRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(items => items.Count == 1
&& items.First().ArtistName == "Queen"
&& items.First().ReleaseType == MusicReleaseType.Album
&& items.First().ReleaseYear == 1975
&& items.First().ReleaseName == "A Night at the Opera"
&& items.First().TrackNumber == 11
&& items.First().DiscNumber == 1
&& items.First().TrackTitle == "Bohemian Rhapsody"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheStagingInsertFails_ShouldMarkJobAsFailed()
{
// Arrange
SetupLibrary();
SetupPaths(AUDIO_FILE_PATH);
_mockMusicMetadataRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<MusicLibraryScanItemMetadataEntity>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to stage the extracted metadata"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheJobIsCompleted_ShouldPublishProgressAndCallTheChildren()
{
// Arrange
SetupLibrary();
SetupPaths(AUDIO_FILE_PATH);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockDomainEventPublisher.Received().PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Stubs the media library reader with a library whose single content location is the test root path.
/// </summary>
private void SetupLibrary()
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Music,
contentLocations: [ROOT_PATH]);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
/// <summary>
/// Stubs the staging results repository with the paths that need their metadata extracted.
/// </summary>
/// <param name="paths">The file system paths that need their metadata extracted.</param>
private void SetupPaths(params string[] paths)
{
_mockStagingResultsRepository.GetPathsNeedingRehashAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(paths));
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("Bohemian Rhapsody");
_mockPathService.GetFileName(Arg.Any<string>()).Returns("Bohemian Rhapsody.mp3");
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanArtworkEnrichmentJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanArtworkEnrichmentJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaLibraryScanArtworkEnricher _mockArtworkEnricher;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanArtworkEnrichmentJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanArtworkEnrichmentJobTests"/> class.
/// </summary>
public MediaLibraryScanArtworkEnrichmentJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
// The job resolves the artwork enricher of the loaded library type from the service scope, so the music enricher must be available.
_mockArtworkEnricher = Substitute.For<IMediaLibraryScanArtworkEnricher>();
_mockArtworkEnricher.SupportedLibraryType.Returns(LibraryType.Music);
_mockArtworkEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanArtworkEnricher>))
.Returns(new IMediaLibraryScanArtworkEnricher[] { _mockArtworkEnricher });
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanArtworkEnrichmentJob(_mockServiceScopeFactory)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockArtworkEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockArtworkEnricher.DidNotReceive().EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,146 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanDiffJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanDiffJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanDiffJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanDiffJobTests"/> class.
/// </summary>
public MediaLibraryScanDiffJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanDiffJob(_mockServiceScopeFactory)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldCompleteAndPublishProgress()
{
// Arrange
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenMarkingChangesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to mark the changes against the snapshot"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldExecuteTheChildJobs()
{
// Arrange
_mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
_sut.AddChild(mockChild);
Guid id = Guid.NewGuid();
object input = new();
// Act
await _sut.ExecuteAsync(id, input, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await mockChild.Received(1).ExecuteAsync(id, input, Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,379 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanHashJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanHashJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly IFileHashService _mockFileHashService;
private readonly MediaLibraryScanHashJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanHashJobTests"/> class.
/// </summary>
public MediaLibraryScanHashJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_mockFileHashService = Substitute.For<IFileHashService>();
_mockServiceProvider.GetService(typeof(IFileHashService)).Returns(_mockFileHashService);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanHashJob(_mockServiceScopeFactory)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: true)));
}
[Fact]
public async Task ExecuteAsync_WhenFilesNeedHashing_ShouldHashAndPersistThemAndComplete()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(2));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
Arg.Is<bool>(shouldParallelizeReads => shouldParallelizeReads),
Arg.Any<Func<Task>>(),
Arg.Any<CancellationToken>());
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
_scanId.Value,
Arg.Is<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.Count == 2 && files.All(file => file.CurrentHash == 42UL)),
Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryIsNotOnSsd_ShouldHashTheFilesSequentially()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, userId: _userId.Value, isContentOnSsd: false)));
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(
Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(),
Arg.Is<bool>(shouldParallelizeReads => !shouldParallelizeReads),
Arg.Any<Func<Task>>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(0));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<bool>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCountingFilesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to count the files to hash"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheFilesToHashPageFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the files to hash"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenUpdatingTheFileHashesFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(2));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.FromResult(callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList()));
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to update the file hashes"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockFileHashService.Received(1).HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheHashingCallbackRunsBeforeTheProgressInterval_ShouldNotPublishJobProgressFromTheCallback()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await callInfo.Arg<Func<Task>>()();
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList();
});
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync(
_scanId.Value,
Arg.Is<IReadOnlyCollection<HashedFileSystemFileDto>>(files => files.All(file => file.CurrentHash == 42UL)),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheHashingCallbackRunsAfterTheProgressInterval_ShouldPublishJobProgressFromTheCallback()
{
// Arrange
List<HashedFileSystemFileDto> filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf")];
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(1));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<HashedFileSystemFileDto>>(filesToHash),
Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
_mockFileHashService.HashFilesAsync(Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<bool>(), Arg.Any<Func<Task>>(), Arg.Any<CancellationToken>())
.Returns(async callInfo =>
{
await Task.Delay(150);
await callInfo.Arg<Func<Task>>()();
return callInfo.Arg<IReadOnlyCollection<HashedFileSystemFileDto>>()
.Select(file => file with { CurrentHash = 42UL })
.ToList();
});
_mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any<IReadOnlyCollection<HashedFileSystemFileDto>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
// The initial progress and the progress published from the hashing callback are both reported.
await _mockDomainEventPublisher.Received(2).PublishAsync(Arg.Is<LibraryScanJobProgressChangedDomainEvent>(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenTheJobHasChildJobs_ShouldExecuteThemAfterCompletingItsPayload()
{
// Arrange
_mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(0));
_mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<HashedFileSystemFileDto>>([]));
IMediaLibraryScanJob mockChildJob = Substitute.For<IMediaLibraryScanJob>();
mockChildJob.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_sut.AddChild(mockChildJob);
Guid id = Guid.NewGuid();
object input = new();
// Act
await _sut.ExecuteAsync(id, input, CancellationToken.None);
// Assert
await mockChildJob.Received(1).ExecuteAsync(id, input, Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
}
@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanMetadataEnrichmentJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanMetadataEnrichmentJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaLibraryScanMetadataEnricher _mockMetadataEnricher;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanMetadataEnrichmentJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanMetadataEnrichmentJobTests"/> class.
/// </summary>
public MediaLibraryScanMetadataEnrichmentJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
// The job resolves the metadata enricher of the loaded library type from the service scope, so the music enricher must be available.
_mockMetadataEnricher = Substitute.For<IMediaLibraryScanMetadataEnricher>();
_mockMetadataEnricher.SupportedLibraryType.Returns(LibraryType.Music);
_mockMetadataEnricher.EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanMetadataEnricher>))
.Returns(new IMediaLibraryScanMetadataEnricher[] { _mockMetadataEnricher });
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenEnrichmentSucceeds_ShouldPublishProgressChangedEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Music);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockMetadataEnricher.Received(1).EnrichAsync(_libraryId, _scanId, _userId, Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockMetadataEnricher.DidNotReceive().EnrichAsync(Arg.Any<LibraryId>(), Arg.Any<ScanId>(), Arg.Any<UserId>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,473 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
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.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanProviderConfigurationInvalidationJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanProviderConfigurationInvalidationJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MediaLibraryScanProviderConfigurationInvalidationJob> _mockLogger;
private readonly MediaLibraryScanProviderConfigurationInvalidationJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanProviderConfigurationInvalidationJobTests"/> class.
/// </summary>
public MediaLibraryScanProviderConfigurationInvalidationJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockArtworkConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
// The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available.
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(Substitute.For<ILibraryPathTemplateService>(), Substitute.For<IPathService>()) });
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProviderConfigurationInvalidationJob>>();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_sut = new MediaLibraryScanProviderConfigurationInvalidationJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenNoFingerprintIsStored_ShouldSeedTheFingerprintsWithoutResettingAnything()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: null);
SetupLibraryAndConfigurations(library);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// A missing stored fingerprint means the configuration was never recorded yet, so the current state of the books is trusted.
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenFingerprintsArePersisted_ShouldPublishProgressChangedEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenMetadataFingerprintDiffers_ShouldResetTheMetadataStatus()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE", artworkProvidersConfigurationFingerprint: null);
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The metadata provider configuration changed, so the books must be re-enriched by the metadata enrichment job.
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenArtworkFingerprintDiffers_ShouldResetTheArtworkStatus()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE");
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The artwork provider configuration changed, so the artwork of the books must be re-resolved by the artwork enrichment job.
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenFingerprintsMatch_ShouldNotResetAnythingButStillPersistTheFingerprints()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
List<LibraryMetadataProviderConfigurationEntity> metadataConfigurations = _libraryMetadataProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
List<LibraryArtworkProviderConfigurationEntity> artworkConfigurations = _libraryArtworkProviderConfigurationEntityFixture.CreateMany(2, _libraryId.Value, Guid.NewGuid(), 1);
SetupLibraryAndConfigurations(library, metadataConfigurations, artworkConfigurations);
// The stored fingerprints match the ones computed from the current provider configuration.
string metadataFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(metadataConfigurations, false, library.CanDownloadMetadataFromWeb);
string artworkFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(artworkConfigurations, false, library.CanDownloadMetadataFromWeb);
library.MetadataProvidersConfigurationFingerprint = metadataFingerprint;
library.ArtworkProvidersConfigurationFingerprint = artworkFingerprint;
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The configuration did not change, so the enrichment state of the books is trusted, and only the fingerprints are persisted.
await _mockBookRepository.DidNotReceive().ResetMetadataStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenBothFingerprintsDiffer_ShouldPersistTheUpdatedFingerprintsViaSaveChangesOnly()
{
// Arrange
// Both fingerprints are stale, so both enrichment channels must be reset and both fingerprints must be rewritten on the tracked entity.
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// Regression guard for the content-location data-loss bug: the fingerprints are persisted on the already-tracked entity and
// flushed through SaveChanges, the repository update action (which clears and re-adds the owned content locations) must never run.
await _mockBookRepository.Received(1).ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the media library"));
SetupConfigurations();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingMetadataConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingArtworkConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the artwork provider configurations"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenResettingMetadataStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: "STALE_METADATA", artworkProvidersConfigurationFingerprint: null);
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetMetadataStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to reset the metadata status"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockBookRepository.DidNotReceive().ResetArtworkStatusForLibraryAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenResettingArtworkStatusFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library", metadataProvidersConfigurationFingerprint: null, artworkProvidersConfigurationFingerprint: "STALE_ARTWORK");
SetupLibraryAndConfigurations(library);
_mockBookRepository.ResetArtworkStatusForLibraryAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to reset the artwork status"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenReadingUserSettingsFails_ShouldStillSeedTheFingerprintsAndComplete()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
IUserSettingsRepository mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
mockUserSettingsRepository.GetByUserIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to read the user settings"));
_mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// Reading the user settings is best effort, a failure must not prevent the fingerprints from being persisted.
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenUserSettingsRepositoryIsNotRegistered_ShouldSeedTheFingerprintsAndComplete()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
_mockUnitOfWork.UserSettingsRepository.Returns((IUserSettingsRepository)null!);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The user settings repository is optional, its absence must not prevent the fingerprints from being persisted.
Assert.NotNull(library.MetadataProvidersConfigurationFingerprint);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildAndComplete()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId.Value, title: "My Library");
SetupLibraryAndConfigurations(library);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
object input = new();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Stubs the repositories so that the job reads the provided library and its provider configurations.
/// </summary>
/// <param name="library">The media library the job must read.</param>
/// <param name="metadataConfigurations">The metadata provider configurations of the media library.</param>
/// <param name="artworkConfigurations">The artwork provider configurations of the media library.</param>
private void SetupLibraryAndConfigurations(LibraryEntity library, List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
{
// The job resolves the materializer by the library type, so the fixture-provided library must be of the type the books materializer supports.
library.LibraryType = LibraryType.Book;
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
SetupConfigurations(metadataConfigurations, artworkConfigurations);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
}
/// <summary>
/// Stubs the provider configuration repositories and the user settings repository used by the job.
/// </summary>
/// <param name="metadataConfigurations">The metadata provider configurations of the media library, if already created by the caller.</param>
/// <param name="artworkConfigurations">The artwork provider configurations of the media library, if already created by the caller.</param>
private void SetupConfigurations(List<LibraryMetadataProviderConfigurationEntity>? metadataConfigurations = null, List<LibraryArtworkProviderConfigurationEntity>? artworkConfigurations = null)
{
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>(
metadataConfigurations ?? [
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
]));
_mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>(
artworkConfigurations ?? [
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 1),
_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, Guid.NewGuid(), 2)
]));
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);
}
}
@@ -0,0 +1,464 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
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.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanResultsSaveJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanResultsSaveJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanResultsSaveJob _sut;
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanResultsSaveJobTests"/> class.
/// </summary>
public MediaLibraryScanResultsSaveJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockSnapshotRepository = Substitute.For<ILibraryScanSnapshotRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
// By default no book exists yet, so every scanned path is materialized; the tests that need existing books override this.
_mockBookRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
// The job resolves the materializer of the loaded library type from the service scope, so the books materializer must be available.
ILibraryPathTemplateService mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
IPathService mockPathService = Substitute.For<IPathService>();
mockPathService.GetFileName(Arg.Any<string>()).Returns(callInfo => callInfo.Arg<string>());
mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns(callInfo =>
{
string fileName = callInfo.Arg<string>();
int lastDotIndex = fileName.LastIndexOf('.');
return lastDotIndex <= 0 ? fileName : fileName[..lastDotIndex];
});
_mockServiceProvider.GetService(typeof(IEnumerable<IMediaLibraryScanItemMaterializer>))
.Returns(new IMediaLibraryScanItemMaterializer[] { new BooksMediaLibraryScanItemMaterializer(mockPathTemplateService, mockPathService) });
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(_libraryEntityFixture.Create(id: _libraryId.Value, libraryType: LibraryType.Book)));
_sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldCreateShellBooksAndPublishFinishedEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["deleted.pdf"]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet("book1.pdf", "book2.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryMediaItemDeletedDomainEvent>(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Is<IReadOnlyCollection<string>>(paths => paths.Any(path => path == "changed.pdf")), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFinishedDomainEvent>(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldPublishProgressChangedEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanProgressChangedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenNoContentChanged_ShouldNotResetTheEnrichmentState()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// No book content changed since the last scan, so the enrichment state of the books must not be reset.
await _mockBookRepository.DidNotReceive().ResetEnrichmentStateForPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet("existing.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>(["existing.pdf"]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingDeletedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the deleted paths"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenGettingChangedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the changed paths"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockSnapshotRepository.DidNotReceive().ApplySnapshotSwapAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenApplyingSnapshotSwapFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to apply the snapshot swap"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenResettingEnrichmentStateFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>(["changed.pdf"]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockBookRepository.ResetEnrichmentStateForPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to reset the enrichment state"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the paths"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenGettingExistingPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet("book1.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to get the existing paths"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenInsertingShellBookFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet("book1.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to insert the shell book"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenJobHasLinkedChildren_ShouldExecuteEachChildWithoutPublishingFinishedEvent()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet()));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
IMediaLibraryScanJob mockChild = Substitute.For<IMediaLibraryScanJob>();
mockChild.ExecuteAsync(Arg.Any<Guid>(), Arg.Any<object>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_sut.AddChild(mockChild);
object input = new();
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), input, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await mockChild.Received(1).ExecuteAsync(Arg.Any<Guid>(), Arg.Is<object>(executedInput => executedInput == input), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<LibraryScanFinishedDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenBookPathYieldsEmptyDerivedTitle_ShouldFallBackToTheFileNameAsTitle()
{
// Arrange
_mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockStagingResultsRepository.GetChangedPathsAsync(_scanId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<string>>([]));
_mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
_mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result.From(CreatePathSet("_.pdf")));
_mockBookRepository.GetExistingPathsAsync(_libraryId.Value, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
// The file name is made only of separators, so the derived title is empty and the raw file name is used as a fallback.
await _mockBookRepository.Received(1).InsertAsync(Arg.Is<BookEntity>(book => book.Path == "_.pdf" && book.Title == "_"), Arg.Any<CancellationToken>());
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the snapshot repository returns.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}
@@ -0,0 +1,198 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="ProviderConfigurationFingerprint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ProviderConfigurationFingerprintTests
{
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
[Fact]
public void ComputeMetadataFingerprint_WhenCalledWithTheSameConfiguration_ShouldReturnTheSameFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<LibraryMetadataProviderConfigurationEntity> configurations =
[
_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0),
_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1)
];
// Act
string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
// Assert
Assert.Equal(firstFingerprint, secondFingerprint);
}
[Fact]
public void ComputeMetadataFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntity first = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
LibraryMetadataProviderConfigurationEntity second = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1);
// Act
string firstFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([first, second], false, true);
string secondFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([second, first], false, true);
// Assert
Assert.Equal(firstFingerprint, secondFingerprint);
}
[Fact]
public void ComputeMetadataFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
LibraryMetadataProviderConfigurationEntity enabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: true);
LibraryMetadataProviderConfigurationEntity disabled = _libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, pluginId, rank: 0, isEnabled: false);
// Act
string enabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([enabled], false, true);
string disabledFingerprint = ProviderConfigurationFingerprint.ComputeMetadataFingerprint([disabled], false, true);
// Assert
Assert.NotEqual(enabledFingerprint, disabledFingerprint);
}
[Fact]
public void ComputeMetadataFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<LibraryMetadataProviderConfigurationEntity> configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
// Act
string withoutAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
string withAggregation = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, true, true);
// Assert
Assert.NotEqual(withoutAggregation, withAggregation);
}
[Fact]
public void ComputeMetadataFingerprint_WhenTheWebAccessSettingChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<LibraryMetadataProviderConfigurationEntity> configurations = [_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
// Act
string withoutWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, false);
string withWebAccess = ProviderConfigurationFingerprint.ComputeMetadataFingerprint(configurations, false, true);
// Assert
Assert.NotEqual(withoutWebAccess, withWebAccess);
}
[Fact]
public void ComputeArtworkFingerprint_WhenOnlyTheOrderOfConfigurationsDiffers_ShouldReturnTheSameFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 1);
// Act
string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first, second], false, true);
string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second, first], false, true);
// Assert
Assert.Equal(firstFingerprint, secondFingerprint);
}
[Fact]
public void ComputeArtworkFingerprint_WhenAProviderChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderConfigurationEntity first = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
LibraryArtworkProviderConfigurationEntity second = _libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0);
// Act
string firstFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([first], false, true);
string secondFingerprint = ProviderConfigurationFingerprint.ComputeArtworkFingerprint([second], false, true);
// Assert
Assert.NotEqual(firstFingerprint, secondFingerprint);
}
[Fact]
public void ComputeArtworkFingerprint_WhenTheAggregationSettingChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
Guid libraryId = Guid.NewGuid();
List<LibraryArtworkProviderConfigurationEntity> configurations = [_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId, Guid.NewGuid(), rank: 0)];
// Act
string withoutAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, false, true);
string withAggregation = ProviderConfigurationFingerprint.ComputeArtworkFingerprint(configurations, true, true);
// Assert
Assert.NotEqual(withoutAggregation, withAggregation);
}
[Fact]
public void ComputePathTemplateFingerprint_WhenOnlyTheOrderOfPartsDiffers_ShouldReturnTheSameFingerprint()
{
// Arrange
LibraryPathTemplatePartEntity first = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}");
LibraryPathTemplatePartEntity second = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.ReleaseName, representation: "{0}");
// Act
string firstFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([first, second]);
string secondFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([second, first]);
// Assert
Assert.Equal(firstFingerprint, secondFingerprint);
}
[Fact]
public void ComputePathTemplateFingerprint_WhenAPartChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
LibraryPathTemplatePartEntity artist = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}");
LibraryPathTemplatePartEntity releaseName = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.ReleaseName, representation: "{0}");
// Act
string artistFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([artist]);
string releaseNameFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([releaseName]);
// Assert
Assert.NotEqual(artistFingerprint, releaseNameFingerprint);
}
[Fact]
public void ComputePathTemplateFingerprint_WhenTheOptionalityChanges_ShouldReturnADifferentFingerprint()
{
// Arrange
LibraryPathTemplatePartEntity required = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity optional = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Act
string requiredFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([required]);
string optionalFingerprint = ProviderConfigurationFingerprint.ComputePathTemplateFingerprint([optional]);
// Assert
Assert.NotEqual(requiredFingerprint, optionalFingerprint);
}
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common;
/// <summary>
/// Contains unit tests for the <see cref="ScanFailurePublisher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScanFailurePublisherTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScanFailurePublisherTests"/> class.
/// </summary>
public ScanFailurePublisherTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
}
[Fact]
public async Task PublishAsync_WhenCalled_ShouldPublishLibraryScanFailedDomainEvent()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
Exception exception = new("The scan job failed");
// Act
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, exception, CancellationToken.None);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(
Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == libraryId
&& domainEvent.MediaLibraryScanCompositeId == compositeId
&& domainEvent.ErrorMessage.HasValue && domainEvent.ErrorMessage.Value == "The scan job failed"),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task PublishAsync_WhenPublisherThrows_ShouldNotThrow()
{
// Arrange
LibraryId libraryId = _libraryIdFixture.Create();
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(callInfo => new ValueTask(Task.FromException(new InvalidOperationException("Publishing failed"))));
// Act
Exception? caughtException = null;
try
{
await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, new Exception("boom"), CancellationToken.None);
}
catch (Exception exception)
{
caughtException = exception;
}
// Assert
Assert.Null(caughtException);
}
}
@@ -0,0 +1,219 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Contains unit tests for the <see cref="BooksFileSystemDiscoveryJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksFileSystemDiscoveryJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<BooksFileSystemDiscoveryJob> _mockLogger;
private readonly BooksFileSystemDiscoveryJob _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="BooksFileSystemDiscoveryJobTests"/> class.
/// </summary>
public BooksFileSystemDiscoveryJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockStagingResultsRepository = Substitute.For<ILibraryScanStagingResultsRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
_mockLogger = Substitute.For<ILogger<BooksFileSystemDiscoveryJob>>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory, _mockLogger)
{
ScanId = _scanId,
UserId = _userId,
LibraryId = _libraryId
};
}
[Fact]
public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the library"));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId
&& domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId
&& domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent()
{
// Arrange
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(null));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status);
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is<LibraryScanFailedDomainEvent>(domainEvent =>
domainEvent.LibraryId == _libraryId), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operation);
Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status);
}
[Fact]
public async Task ExecuteAsync_WhenTheLibraryIsOnSsd_ShouldLogThatTheFileSystemReadsRunInParallel()
{
// Arrange
string temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-books-ssd-{Guid.NewGuid()}");
Directory.CreateDirectory(temporaryDirectoryPath);
File.WriteAllText(Path.Combine(temporaryDirectoryPath, "book.pdf"), "book content");
try
{
LibraryEntity libraryEntity = _libraryEntityFixture.Create(
id: _libraryId.Value,
userId: _userId.Value,
libraryType: LibraryType.Book,
contentLocations: [temporaryDirectoryPath],
isContentOnSsd: true);
_mockLibraryRepository.GetByIdAsync(_libraryId.Value, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(libraryEntity));
_mockStagingResultsRepository.InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
// Act
await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None);
// Assert
Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status);
await _mockStagingResultsRepository.Received(1).InsertRangeAsync(
Arg.Is<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(entities => entities.Count == 1 && Path.GetFileName(entities.First().Path) == "book.pdf"),
Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Debug,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("solid state drive", StringComparison.Ordinal)),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
finally
{
Directory.Delete(temporaryDirectoryPath, recursive: true);
}
}
[Fact]
public async Task StageFilesInParallelAsync_WhenAFileVanishesBeforeItsMetadataIsRead_ShouldSkipItAndLogAWarning()
{
// Arrange
FileInfo vanishedFile = new(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(), "vanished.pdf"));
List<LibraryScanStagingResultsEntity> stagingBatch = [];
// Act
await _sut.StageFilesInParallelAsync([vanishedFile], stagingBatch, _mockStagingResultsRepository, CancellationToken.None);
// Assert
Assert.Empty(stagingBatch);
await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any<IReadOnlyCollection<LibraryScanStagingResultsEntity>>(), Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("vanished.pdf", StringComparison.Ordinal)),
Arg.Any<IOException>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StageFilesInParallelAsync_WhenAFileReadThrowsAnUnexpectedException_ShouldRethrowTheRealCause()
{
// Arrange
List<LibraryScanStagingResultsEntity> stagingBatch = [];
List<FileInfo> files = [null!];
// Act
Exception exception = await Assert.ThrowsAsync<NullReferenceException>(() =>
_sut.StageFilesInParallelAsync(files, stagingBatch, _mockStagingResultsRepository, CancellationToken.None));
// Assert
// Parallel.For wraps the body exception in an AggregateException, which would otherwise be reported as "One or more errors occurred.".
Assert.IsType<NullReferenceException>(exception);
}
}
@@ -0,0 +1,482 @@
#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.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Security;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.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.Contracts.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
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.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.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Contains unit tests for the <see cref="BooksMediaLibraryScanArtworkEnricher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksMediaLibraryScanArtworkEnricherTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository;
private readonly IBookRepository _mockBookRepository;
private readonly IArtworkProvider _mockArtworkProvider;
private readonly IBookArtworkService _mockBookArtworkService;
private readonly IFileHashService _mockFileHashService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<BooksMediaLibraryScanArtworkEnricher> _mockLogger;
private readonly BooksMediaLibraryScanArtworkEnricher _sut;
private readonly ServiceProvider _serviceProvider;
private readonly Guid _pluginId = Guid.NewGuid();
private readonly LibraryId _libraryId;
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanArtworkEnricherTests"/> class.
/// </summary>
public BooksMediaLibraryScanArtworkEnricherTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockArtworkProviderConfigurationRepository = Substitute.For<IArtworkProviderConfigurationRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockArtworkProvider = Substitute.For<IArtworkProvider>();
_mockArtworkProvider.Name.Returns("Test Provider");
_mockArtworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
_mockArtworkProvider.RequiresWebAccess.Returns(true);
_mockBookArtworkService = Substitute.For<IBookArtworkService>();
_mockFileHashService = Substitute.For<IFileHashService>();
_mockFileHashService.ComputeFileHash(Arg.Any<string>()).Returns(123UL);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockLogger = Substitute.For<ILogger<BooksMediaLibraryScanArtworkEnricher>>();
// The enricher resolves the keyed artwork providers from the scope of the service provider, so a real container is used to honor the keyed registration.
ServiceCollection services = new();
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockDomainEventPublisher);
services.AddSingleton(_mockBookArtworkService);
services.AddSingleton(_mockFileHashService);
services.AddKeyedSingleton<IArtworkProvider>(_pluginId, _mockArtworkProvider);
_serviceProvider = services.BuildServiceProvider();
_sut = new BooksMediaLibraryScanArtworkEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), _mockLogger);
_libraryId = _libraryIdFixture.Create();
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
}
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnBook()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Book, result);
}
[Fact]
public async Task EnrichAsync_WhenNoArtworkProviderIsConfigured_ShouldSkipTheEnrichment()
{
// Arrange
SetupLibrary();
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheArtworkConfigurationsCannotBeRead_ShouldSkipTheEnrichment()
{
// Arrange
SetupLibrary();
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloads_ShouldSkipProvidersThatRequireWebAccess()
{
// Arrange
SetupLibrary(canDownloadMetadataFromWeb: false);
SetupConfiguration();
_mockArtworkProvider.RequiresWebAccess.Returns(true);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookRepository.DidNotReceive().GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheLibraryDisallowsWebDownloadsButTheProviderIsLocal_ShouldStillResolve()
{
// Arrange
SetupLibrary(canDownloadMetadataFromWeb: false);
SetupConfiguration();
_mockArtworkProvider.RequiresWebAccess.Returns(false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockArtworkProvider.Received(1).GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheBookHasArtwork_ShouldStoreAndPersistEnrichedArtwork()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg", type: ArtworkType.Cover, ordinal: 0)]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookArtworkService.Received(1).SaveBookArtworkAsync(
book.LibraryId,
book.Id,
Arg.Any<string>(),
Arg.Any<string>(),
book.Title,
Arg.Is<ArtworkDto>(artwork => artwork.Type == ArtworkType.Cover && artwork.Ordinal == 0),
Arg.Any<CancellationToken>());
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkType.Cover, artwork.ArtworkType);
Assert.Equal(0, artwork.Ordinal);
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
Assert.Equal("Test Provider", artwork.Provider);
Assert.Equal("/media/books/cover.jpg", artwork.FileName);
Assert.Equal(123UL, artwork.ContentHash);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenAProviderAnswersWithNoArtwork_ShouldMarkTheBookFailed()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
Assert.Null(artwork.FileName);
Assert.Null(artwork.Provider);
}
[Fact]
public async Task EnrichAsync_WhenEveryProviderFails_ShouldMarkTheBookFailed()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromException<IReadOnlyList<ArtworkDto>>(new HttpRequestException("Transient failure.")));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
}
[Fact]
public async Task EnrichAsync_WhenTheProviderReturnsRemoteArtworkButDoesNotRequireWebAccess_ShouldMarkTheBookFailed()
{
// Arrange
SetupLibrary();
SetupConfiguration();
_mockArtworkProvider.RequiresWebAccess.Returns(false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
}
[Fact]
public async Task EnrichAsync_WhenTheStoredArtworkIsIdentical_ShouldKeepItAndMarkItEnriched()
{
// Arrange
SetupLibrary();
SetupConfiguration();
_mockArtworkProvider.RequiresWebAccess.Returns(false);
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
BookArtworkEntity existingArtwork = _bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, contentHash: 123UL, status: ArtworkStatus.Enriched);
book.Artwork = [existingArtwork];
SetupBooks(book);
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: "/media/books/local.jpg", remoteUrl: null, type: ArtworkType.Cover, ordinal: 0)]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookArtworkService.DidNotReceive().SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>());
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkStatus.Enriched, artwork.Status);
Assert.Equal("Test Provider", artwork.Provider);
}
[Fact]
public async Task EnrichAsync_WhenStoringTheArtworkFails_ShouldMarkTheBookFailed()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockBookArtworkService.SaveBookArtworkAsync(Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<ArtworkDto>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Artwork.Error", "Failed to store the artwork"));
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
BookArtworkEntity artwork = Assert.Single(book.Artwork);
Assert.Equal(ArtworkStatus.Failed, artwork.Status);
}
[Fact]
public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
SetupLibrary();
SetupConfiguration();
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to count the books"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
SetupLibrary();
SetupConfiguration();
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to read the books"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheAuthorsCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.From(1));
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<BookEntity>>([book]));
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to read the authors"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
{
// Arrange
SetupLibrary();
SetupConfiguration();
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
SetupSuccessStore();
_mockArtworkProvider.GetArtworkAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ArtworkDto>>([_artworkDtoFixture.Create(localPath: null, remoteUrl: "https://covers.openlibrary.org/b/id/1-L.jpg")]));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
SetupLibrary();
SetupConfiguration();
SetupBooks();
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
/// <summary>
/// Stubs the media library reader with a library owned by the test user.
/// </summary>
/// <param name="canDownloadMetadataFromWeb">Whether the library allows downloading data from the web.</param>
private void SetupLibrary(bool canDownloadMetadataFromWeb = true)
{
LibraryEntity library = _libraryEntityFixture.Create(
id: _libraryId.Value,
libraryType: LibraryType.Book,
canDownloadMetadataFromWeb: canDownloadMetadataFromWeb);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
}
/// <summary>
/// Stubs the artwork provider configuration reader with a single enabled configuration for the test plugin.
/// </summary>
private void SetupConfiguration()
{
_mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyList<LibraryArtworkProviderConfigurationEntity>>([_libraryArtworkProviderConfigurationEntityFixture.Create(_libraryId.Value, _pluginId, 0)]));
}
/// <summary>
/// Stubs the book reader with a single page holding the provided books.
/// </summary>
/// <param name="books">The books of the page.</param>
private void SetupBooks(params BookEntity[] books)
{
_mockBookRepository.GetBooksNeedingArtworkCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From(books.Length));
_mockBookRepository.GetBooksNeedingArtworkAsync(Arg.Any<Guid>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result.From<IReadOnlyList<BookEntity>>(books),
Result.From<IReadOnlyList<BookEntity>>([]));
Dictionary<Guid, string?> authors = books.ToDictionary(book => book.Id, book => (string?)"Frank Herbert");
_mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyDictionary<Guid, string?>>(authors));
}
/// <summary>
/// Stubs the artwork storage so that a book stores its artwork successfully.
/// </summary>
private void SetupSuccessStore()
{
_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/cover.jpg"));
}
}
@@ -0,0 +1,138 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Contains unit tests for the <see cref="BooksMediaLibraryScanItemMaterializer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksMediaLibraryScanItemMaterializerTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryPathTemplateService _mockPathTemplateService;
private readonly IPathService _mockPathService;
private readonly BooksMediaLibraryScanItemMaterializer _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly Guid _libraryId;
private readonly Guid _scanId;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanItemMaterializerTests"/> class.
/// </summary>
public BooksMediaLibraryScanItemMaterializerTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockPathTemplateService = Substitute.For<ILibraryPathTemplateService>();
_mockPathService = Substitute.For<IPathService>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_libraryId = Guid.NewGuid();
_scanId = Guid.NewGuid();
// Default stubs: the library has no path template of its own, no book is stored yet, and the separator is the Windows one.
_mockPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>())
.Returns(Result.From(LibraryPathTemplate.Empty()));
_mockPathService.PathSeparator.Returns('\\');
_mockPathService.GetFileNameWithoutExtension(Arg.Any<string>()).Returns("track");
_mockBookRepository.GetExistingPathsAsync(Arg.Any<Guid>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>([]));
_mockBookRepository.InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Created));
_mockPathTemplateService.Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), Arg.Any<string>(), Arg.Any<char>())
.Returns(Result.From(Optional<ParsedLibraryPath>.None()));
_sut = new BooksMediaLibraryScanItemMaterializer(_mockPathTemplateService, _mockPathService);
}
[Fact]
public async Task MaterializeItemsAsync_WhenPathSharesTheContentLocationPrefixButIsOutside_ShouldFallBackToTheFileNameRelativePath()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockPathService.IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music").Returns(false);
_mockPathService.GetFileName("C:\\MusicBackup\\track.epub").Returns("track.epub");
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\MusicBackup\\track.epub"), CancellationToken.None);
// Assert
// A sibling directory whose name only starts with the content location name is not inside the library, so the item is not parsed against
// the path template, and the file name is used as the relative path instead.
Assert.False(result.IsFailure);
_mockPathService.Received(1).IsPathWithin("C:\\MusicBackup\\track.epub", "C:\\Music");
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "track.epub", '\\');
}
[Fact]
public async Task MaterializeItemsAsync_WhenPathIsInsideTheContentLocation_ShouldParseThePathRelativeToTheContentLocation()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockPathService.IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music").Returns(true);
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\Artist\\track.epub"), CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockPathService.Received(1).IsPathWithin("C:\\Music\\Artist\\track.epub", "C:\\Music");
_mockPathTemplateService.Received(1).Parse(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>(), "Artist\\track.epub", '\\');
}
[Fact]
public async Task MaterializeItemsAsync_WhenPathIsAlreadyUsedByADeletedBook_ShouldNotInsertItAgain()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(id: _libraryId, libraryType: LibraryType.Book, contentLocations: ["C:\\Music"]);
_mockLibraryRepository.GetByIdAsync(_libraryId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(library));
_mockBookRepository.GetExistingPathsAsync(_libraryId, Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IReadOnlyCollection<string>>(["C:\\Music\\deleted.epub"]));
// Act
Result<Success> result = await _sut.MaterializeItemsAsync(_mockUnitOfWork, _libraryId, _scanId, CreatePathSet("C:\\Music\\deleted.epub"), CancellationToken.None);
// Assert
// A deleted book keeps its stored path, so the scan treats the file as already catalogued and never materializes it again.
Assert.False(result.IsFailure);
await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any<BookEntity>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Creates the set of media library scan snapshot paths that the media library scan produces.
/// </summary>
/// <param name="paths">The paths of the set.</param>
/// <returns>The set of paths.</returns>
private static IReadOnlySet<string> CreatePathSet(params string[] paths)
{
return new HashSet<string>(paths, StringComparer.Ordinal);
}
}
@@ -0,0 +1,383 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
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.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Users;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaContributors;
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.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors;
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;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
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.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books;
/// <summary>
/// Contains unit tests for the <see cref="BooksMediaLibraryScanMetadataEnricher"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BooksMediaLibraryScanMetadataEnricherTests
{
private const string PROVIDER_A_NAME = "ProviderA";
private const string PROVIDER_B_NAME = "ProviderB";
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IBookRepository _mockBookRepository;
private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository;
private readonly IUserSettingsRepository _mockUserSettingsRepository;
private readonly IMediaContributorRepository _mockMediaContributorRepository;
private readonly IMetadataProvider _mockProviderA;
private readonly IMetadataProvider _mockProviderB;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ServiceProvider _serviceProvider;
private readonly BooksMediaLibraryScanMetadataEnricher _sut;
private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new();
private readonly ScanIdFixture _scanIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
private readonly LibraryIdFixture _libraryIdFixture = new();
private readonly ScanId _scanId;
private readonly UserId _userId;
private readonly LibraryId _libraryId;
/// <summary>
/// Initializes a new instance of the <see cref="BooksMediaLibraryScanMetadataEnricherTests"/> class.
/// </summary>
public BooksMediaLibraryScanMetadataEnricherTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockBookRepository = Substitute.For<IBookRepository>();
_mockMetadataConfigurationRepository = Substitute.For<ILibraryMetadataProviderConfigurationRepository>();
_mockUserSettingsRepository = Substitute.For<IUserSettingsRepository>();
_mockMediaContributorRepository = Substitute.For<IMediaContributorRepository>();
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
_mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository);
_mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository);
_mockUnitOfWork.MediaContributorRepository.Returns(_mockMediaContributorRepository);
_mockProviderA = Substitute.For<IMetadataProvider>();
ConfigureProvider(_mockProviderA, PROVIDER_A_NAME);
_mockProviderB = Substitute.For<IMetadataProvider>();
ConfigureProvider(_mockProviderB, PROVIDER_B_NAME);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockDomainEventPublisher.PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>())
.Returns(ValueTask.CompletedTask);
_scanId = _scanIdFixture.Create();
_userId = _userIdFixture.Create();
_libraryId = _libraryIdFixture.Create();
// The configured providers are registered under the plugin Ids they are configured with, the way the host registers plugin provided services.
Guid pluginAId = Guid.NewGuid();
Guid pluginBId = Guid.NewGuid();
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>.Success(
[
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginAId, rank: 1),
_libraryMetadataProviderConfigurationEntityFixture.Create(_libraryId.Value, pluginBId, rank: 2)
]));
ServiceCollection services = new();
services.AddScoped(_ => _mockUnitOfWork);
services.AddScoped(_ => _mockDomainEventPublisher);
services.AddKeyedTransient(pluginAId, (serviceProvider, serviceKey) => _mockProviderA);
services.AddKeyedTransient(pluginBId, (serviceProvider, serviceKey) => _mockProviderB);
_serviceProvider = services.BuildServiceProvider();
_sut = new BooksMediaLibraryScanMetadataEnricher(_serviceProvider.GetRequiredService<IServiceScopeFactory>(), NullLogger<BooksMediaLibraryScanMetadataEnricher>.Instance);
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(1));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<BookEntity>>.Success([]));
_mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any<CancellationToken>())
.Returns(Result<UserSettingsEntity?>.Success(null));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Success));
}
[Fact]
public async Task EnrichAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipTheEnrichment()
{
// Arrange
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>.Success([]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheMetadataConfigurationsCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
_mockMetadataConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Provider.Error", "Failed to read the configurations"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheFirstProviderReturnsApplicableMetadata_ShouldNotQueryTheFollowingProviders()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.DidNotReceive().GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal(PROVIDER_A_NAME, book.MetadataProvider);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnrichAsync_WhenTheFirstProviderReturnsNoUsableMetadata_ShouldQueryTheFollowingProviders()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)null);
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal(PROVIDER_B_NAME, book.MetadataProvider);
}
[Fact]
public async Task EnrichAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookFailed()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)null);
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)null);
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
Assert.Equal(MetadataStatus.Failed, book.MetadataStatus);
}
[Fact]
public async Task EnrichAsync_WhenAggregationIsEnabled_ShouldQueryEveryProviderAndMergeTheirMetadata()
{
// Arrange
_mockUserSettingsRepository.GetByUserIdAsync(_userId.Value, Arg.Any<CancellationToken>())
.Returns(Result<UserSettingsEntity?>.Success(_userSettingsEntityFixture.Create(userId: _userId.Value, shouldAggregateMetadataWhenMissing: true)));
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
_mockProviderB.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune Messiah"));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockProviderA.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
await _mockProviderB.Received(1).GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>());
Assert.Equal(MetadataStatus.Enriched, book.MetadataStatus);
Assert.Equal($"{PROVIDER_A_NAME}, {PROVIDER_B_NAME}", book.MetadataProvider);
}
[Fact]
public async Task EnrichAsync_WhenTheMetadataHasContributors_ShouldLinkThemToTheBook()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
MediaContributorEntity contributor = _mediaContributorEntityFixture.Create();
_mockMediaContributorRepository.FindOrCreateByDisplayNameAsync(Arg.Any<string>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(Result.From(contributor));
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata(
"Dune",
contributors: [_mediaContributorDtoFixture.Create(displayName: "Frank Herbert", role: MediaContributorRole.Author, legalName: null)]));
// Act
await _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
// Assert
await _mockMediaContributorRepository.Received(1).FindOrCreateByDisplayNameAsync("Frank Herbert", null, Arg.Any<CancellationToken>());
BookContributorEntity linkedContributor = Assert.Single(book.Contributors);
Assert.Equal(contributor.Id, linkedContributor.MediaContributorId);
Assert.Equal(MediaContributorRole.Author, linkedContributor.Role);
}
[Fact]
public async Task EnrichAsync_WhenTheBookCountCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to count the books"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheBooksPageCannotBeRead_ShouldThrowInvalidOperationException()
{
// Arrange
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to read the books"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenSavingTheChangesFails_ShouldThrowInvalidOperationException()
{
// Arrange
BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value);
SetupBooks(book);
_mockProviderA.GetMetadataAsync(Arg.Any<MetadataLookupDto>(), Arg.Any<CancellationToken>())
.Returns((MetadataDto?)CreateApplicableBookMetadata("Dune"));
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>())
.Returns(Error.Failure("Repository.Error", "Failed to save the changes"));
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(Act);
}
[Fact]
public async Task EnrichAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation()
{
// Arrange
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
Task Act()
{
return _sut.EnrichAsync(_libraryId, _scanId, _userId, cancellationTokenSource.Token);
}
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(Act);
}
/// <summary>
/// Stubs the book reader with a single page holding the provided books.
/// </summary>
/// <param name="books">The books of the page.</param>
private void SetupBooks(params BookEntity[] books)
{
_mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any<CancellationToken>())
.Returns(Result<int>.Success(books.Length));
_mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(
Result<IReadOnlyList<BookEntity>>.Success(books),
Result<IReadOnlyList<BookEntity>>.Success([]));
}
/// <summary>
/// Configures the provided substitute metadata provider so that it declares the book lookup type for the books media library type.
/// </summary>
/// <param name="metadataProvider">The metadata provider substitute to configure.</param>
/// <param name="name">The display name the provider reports.</param>
private static void ConfigureProvider(IMetadataProvider metadataProvider, string name)
{
metadataProvider.Name.Returns(name);
metadataProvider.SupportedLibraryTypes.Returns([LibraryType.Book]);
metadataProvider.RequiresWebAccess.Returns(false);
metadataProvider.LookupType.Returns(typeof(BookMetadataLookupDto));
}
/// <summary>
/// Creates a book metadata that is usable and carries only a title, and optionally a set of contributors.
/// </summary>
/// <param name="title">The title of the book.</param>
/// <param name="contributors">The optional contributors of the book.</param>
/// <returns>The created book metadata.</returns>
private BookMetadataDto CreateApplicableBookMetadata(string title, List<MediaContributorDto>? contributors = null)
{
return _bookMetadataDtoFixture.Create(
title: title,
contributors: contributors);
}
}
@@ -0,0 +1,288 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Microsoft.AspNetCore.SignalR;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
/// <summary>
/// Contains unit tests for the <see cref="DebouncedMediaLibraryScanProgressNotifier"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DebouncedMediaLibraryScanProgressNotifierTests
{
private readonly IHubContext<MediaLibraryScanProgressHub> _mockHubContext;
private readonly IHubClients _mockHubClients;
private readonly IClientProxy _mockClientProxy;
private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker;
private readonly DebouncedMediaLibraryScanProgressNotifier _sut;
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="DebouncedMediaLibraryScanProgressNotifierTests"/> class.
/// </summary>
public DebouncedMediaLibraryScanProgressNotifierTests()
{
_mockHubContext = Substitute.For<IHubContext<MediaLibraryScanProgressHub>>();
_mockHubClients = Substitute.For<IHubClients>();
_mockClientProxy = Substitute.For<IClientProxy>();
_mockHubContext.Clients.Returns(_mockHubClients);
_mockHubClients.Group(Arg.Any<string>()).Returns(_mockClientProxy);
_mockClientProxy.SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>())
.Returns(Task.CompletedTask);
_mockProgressTracker = Substitute.For<IMediaLibrariesScanProgressTracker>();
_sut = new DebouncedMediaLibraryScanProgressNotifier(_mockHubContext, _mockProgressTracker);
}
[Fact]
public async Task SendLibraryProgressUpdateEventAsync_WhenTokenIsCancelled_ShouldNotPublishOrQueryProgress()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, cancellationTokenSource.Token);
// Assert
_mockProgressTracker.DidNotReceive().GetScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[Fact]
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressExists_ShouldSendProgressUpdateToGroup()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
scanId: compositeId.ScanId,
userId: compositeId.UserId,
completedJobs: 1,
totalJobs: 2,
status: LibraryScanJobStatus.Running);
_mockProgressTracker.GetScanProgress(compositeId).Returns(Result.From(progress));
// Act
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
// Assert
_mockHubClients.Received(1).Group(compositeId.ToString());
await _mockClientProxy.Received(1).SendCoreAsync(
"libraryScanProgressUpdateEvent",
Arg.Is<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Running.ToString()),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryProgressUpdateEventAsync_WhenProgressIsMissing_ShouldNotSendUpdate()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_mockProgressTracker.GetScanProgress(compositeId)
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
// Act
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanFinishedEventAsync_WhenProgressExists_ShouldSendFinishedEventWithCompletedStatus()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
scanId: compositeId.ScanId,
userId: compositeId.UserId,
completedJobs: 1,
totalJobs: 2,
status: LibraryScanJobStatus.Running);
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
// Act
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.Received(1).SendCoreAsync(
"libraryScanFinishedEvent",
Arg.Is<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanFinishedEventAsync_WhenProgressIsMissing_ShouldNotSendFinishedEvent()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_mockProgressTracker.RemoveScanProgress(compositeId)
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
// Act
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanFailedEventAsync_WhenProgressExists_ShouldSendFailedEventWithFailedStatus()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
scanId: compositeId.ScanId,
userId: compositeId.UserId,
completedJobs: 1,
totalJobs: 2,
status: LibraryScanJobStatus.Running);
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
// Act
await _sut.SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.Received(1).SendCoreAsync(
"libraryScanFailedEvent",
Arg.Is<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanFinishedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
await _sut.SendLibraryScanFinishedEventAsync(compositeId, cancellationTokenSource.Token);
// Assert
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[Fact]
public async Task SendLibraryScanFailedEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
await _sut.SendLibraryScanFailedEventAsync(compositeId, cancellationTokenSource.Token);
// Assert
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[Fact]
public async Task SendLibraryScanCancelledEventAsync_WhenProgressExists_ShouldSendCancelledEventWithCanceledStatus()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
scanId: compositeId.ScanId,
userId: compositeId.UserId,
completedJobs: 1,
totalJobs: 2,
status: LibraryScanJobStatus.Pending);
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
// Act
await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.Received(1).SendCoreAsync(
"libraryScanCancelledEvent",
Arg.Is<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Canceled.ToString()),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanCancelledEventAsync_WhenProgressIsMissing_ShouldNotSendCancelledEvent()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
_mockProgressTracker.RemoveScanProgress(compositeId)
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
// Act
await _sut.SendLibraryScanCancelledEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any<string>(), Arg.Any<object?[]>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SendLibraryScanCancelledEventAsync_WhenTokenIsCancelled_ShouldNotRemoveProgressOrSendEvent()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
using CancellationTokenSource cancellationTokenSource = new();
cancellationTokenSource.Cancel();
// Act
await _sut.SendLibraryScanCancelledEventAsync(compositeId, cancellationTokenSource.Token);
// Assert
_mockProgressTracker.DidNotReceive().RemoveScanProgress(Arg.Any<MediaLibraryScanCompositeId>());
_mockHubClients.DidNotReceive().Group(Arg.Any<string>());
}
[Fact]
public async Task SendLibraryScanFinishedEventAsync_WhenADebouncedUpdateWasScheduledForTheScan_ShouldRemoveTheDebouncer()
{
// Arrange
MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create();
// The scheduled update is registered by the progress update even when the progress is missing, which also avoids sending an update event.
_mockProgressTracker.GetScanProgress(compositeId)
.Returns(Error.Failure("Tracking.Error", "The scan progress is missing"));
MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create(
scanId: compositeId.ScanId,
userId: compositeId.UserId,
completedJobs: 1,
totalJobs: 2,
status: LibraryScanJobStatus.Running);
_mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress));
// Act
await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None);
await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None);
// Assert
await _mockClientProxy.Received(1).SendCoreAsync(
"libraryScanFinishedEvent",
Arg.Is<object?[]>(args => args.Length == 1
&& args[0] != null
&& ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()),
Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress;
using Microsoft.AspNetCore.SignalR;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanProgressHub"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanProgressHubTests
{
[Fact]
public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheGroupOfTheAuthenticatedUser()
{
// Arrange
MediaLibraryScanProgressHub sut = new();
HubCallerContext context = Substitute.For<HubCallerContext>();
context.ConnectionId.Returns("connection-1");
IGroupManager groupManager = Substitute.For<IGroupManager>();
sut.Context = context;
sut.Groups = groupManager;
Guid scanId = Guid.NewGuid();
Guid userId = Guid.NewGuid();
// The user is always taken from the authenticated connection, never from the client.
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
context.User.Returns(user);
// Act
await sut.SubscribeToScan(scanId);
// Assert
await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None);
}
[Fact]
public async Task SubscribeToScan_WhenUserClaimIsMissing_ShouldNotAddTheConnectionToAnyGroup()
{
// Arrange
MediaLibraryScanProgressHub sut = new();
HubCallerContext context = Substitute.For<HubCallerContext>();
context.ConnectionId.Returns("connection-1");
IGroupManager groupManager = Substitute.For<IGroupManager>();
sut.Context = context;
sut.Groups = groupManager;
Guid scanId = Guid.NewGuid();
ClaimsPrincipal user = new(new ClaimsIdentity());
context.User.Returns(user);
// Act
await sut.SubscribeToScan(scanId);
// Assert
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SubscribeToScan_WhenUserIdClaimIsNotAGuid_ShouldNotAddTheConnectionToAnyGroup()
{
// Arrange
MediaLibraryScanProgressHub sut = new();
HubCallerContext context = Substitute.For<HubCallerContext>();
context.ConnectionId.Returns("connection-1");
IGroupManager groupManager = Substitute.For<IGroupManager>();
sut.Context = context;
sut.Groups = groupManager;
Guid scanId = Guid.NewGuid();
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")]));
context.User.Returns(user);
// Act
await sut.SubscribeToScan(scanId);
// Assert
await groupManager.DidNotReceive().AddToGroupAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,73 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibrariesScanQueue"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibrariesScanQueueTests
{
private readonly MediaLibrariesScanQueue _sut = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
[Fact]
public async Task Writer_WhenScanIsWritten_ShouldAllowReadingItFromReader()
{
// Arrange
MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
bool writeResult = _sut.Writer.TryWrite(scanId);
MediaLibraryScanCompositeId readScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
// Assert
Assert.True(writeResult);
Assert.Equal(scanId, readScanId);
}
[Fact]
public async Task Writer_WhenMultipleScansAreWritten_ShouldReadThemInFifoOrder()
{
// Arrange
MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId thirdScanId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
_sut.Writer.TryWrite(firstScanId);
_sut.Writer.TryWrite(secondScanId);
_sut.Writer.TryWrite(thirdScanId);
MediaLibraryScanCompositeId firstReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
MediaLibraryScanCompositeId secondReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
MediaLibraryScanCompositeId thirdReadScanId = await _sut.Reader.ReadAsync(CancellationToken.None);
// Assert
// The scan processor relies on the queue order: scans must run in the order in which they were queued.
Assert.Equal(firstScanId, firstReadScanId);
Assert.Equal(secondScanId, secondReadScanId);
Assert.Equal(thirdScanId, thirdReadScanId);
}
[Fact]
public async Task Reader_WhenQueueIsEmpty_ShouldNotCompleteUntilAScanIsWritten()
{
// Arrange
MediaLibraryScanCompositeId scanId = _mediaLibraryScanCompositeIdFixture.Create();
// Act
Task<MediaLibraryScanCompositeId> readTask = _sut.Reader.ReadAsync(CancellationToken.None).AsTask();
_sut.Writer.TryWrite(scanId);
// Assert
MediaLibraryScanCompositeId readScanId = await readTask;
Assert.Equal(scanId, readScanId);
}
}
@@ -0,0 +1,320 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanProcessorJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanProcessorJobTests : IDisposable
{
private static readonly TimeSpan s_testTimeout = TimeSpan.FromSeconds(5);
private readonly MediaLibrariesScanQueue _queue;
private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly ILogger<MediaLibraryScanProcessorJob> _mockLogger;
private readonly ServiceProvider _serviceProvider;
private readonly MediaLibraryScanProcessorJob _sut;
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new();
private readonly MediaLibraryScanDiscoveryJobFixture _mediaLibraryScanDiscoveryJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanProcessorJobTests"/> class.
/// </summary>
public MediaLibraryScanProcessorJobTests()
{
_queue = new MediaLibrariesScanQueue();
_mockCancellationTracker = Substitute.For<IMediaLibrariesScanCancellationTracker>();
_mockCancellationTracker.GetTokenForScan(Arg.Any<MediaLibraryScanCompositeId>()).Returns(CancellationToken.None);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
_mockMediaLibraryScanningService = Substitute.For<IMediaLibraryScanningService>();
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_mockLogger = Substitute.For<ILogger<MediaLibraryScanProcessorJob>>();
ServiceCollection services = new();
services.AddSingleton(_mockUnitOfWork);
services.AddSingleton(_mockMediaLibraryScanningService);
services.AddSingleton(_mockDomainEventPublisher);
_serviceProvider = services.BuildServiceProvider();
_sut = new MediaLibraryScanProcessorJob(
_queue,
_mockCancellationTracker,
_serviceProvider.GetRequiredService<IServiceScopeFactory>(),
_mockLogger);
}
[Fact]
public async Task ExecuteAsync_WhenScansAreQueued_ShouldProcessThemOneAtATimeInOrder()
{
// Arrange
MediaLibraryScanCompositeId firstScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId secondScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(firstScanId, LibraryScanJobStatus.Pending);
RegisterScan(secondScanId, LibraryScanJobStatus.Pending);
TaskCompletionSource<bool> releaseFirstScan = new(TaskCreationOptions.RunContinuationsAsynchronously);
// ExecutionStarted is signaled before the callback runs, and resumes the test on another thread, so the test waits for the callback itself to record the scan.
TaskCompletionSource firstScanRecorded = new(TaskCreationOptions.RunContinuationsAsynchronously);
List<Guid> startedScanIds = [];
FakeMediaLibraryScanDiscoveryJob firstRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: async _ =>
{
startedScanIds.Add(firstScanId.ScanId.Value);
firstScanRecorded.SetResult();
await releaseFirstScan.Task;
});
FakeMediaLibraryScanDiscoveryJob secondRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(onExecute: _ =>
{
startedScanIds.Add(secondScanId.ScanId.Value);
return Task.CompletedTask;
});
RegisterRootJob(firstScanId, firstRootJob);
RegisterRootJob(secondScanId, secondRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(firstScanId);
_queue.Writer.TryWrite(secondScanId);
await firstScanRecorded.Task.WaitAsync(s_testTimeout);
// Assert
// The second scan must not start while the job graph of the first one is still executing.
Assert.Equal([firstScanId.ScanId.Value], startedScanIds);
Assert.Equal(0, secondRootJob.ExecutionCount);
releaseFirstScan.SetResult(true);
await secondRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
Assert.Equal([firstScanId.ScanId.Value, secondScanId.ScanId.Value], startedScanIds);
Assert.Equal(1, firstRootJob.ExecutionCount);
await _sut.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_WhenScanIsNotPending_ShouldSkipItAndProcessTheNextScan()
{
// Arrange
MediaLibraryScanCompositeId completedScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(completedScanId, LibraryScanJobStatus.Completed);
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterRootJob(pendingScanId, pendingRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(completedScanId);
_queue.Writer.TryWrite(pendingScanId);
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
// Assert
// A scan that was cancelled or otherwise finished while it was waiting for its turn must not be started.
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == completedScanId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>());
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
await _sut.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_WhenScanTokenIsAlreadyCancelled_ShouldSkipItAndProcessTheNextScan()
{
// Arrange
MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending);
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
using CancellationTokenSource cancelledTokenSource = new();
cancelledTokenSource.Cancel();
_mockCancellationTracker.GetTokenForScan(cancelledScanId).Returns(cancelledTokenSource.Token);
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterRootJob(pendingScanId, pendingRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(cancelledScanId);
_queue.Writer.TryWrite(pendingScanId);
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
// Assert
// A scan that was cancelled while it was waiting for its turn is not even loaded from the repository.
await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(
cancelledScanId.ScanId.Value,
Arg.Any<bool>(),
false,
Arg.Any<CancellationToken>());
await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == cancelledScanId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>());
await _mockMediaLibraryScanningService.Received(1).StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == pendingScanId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>());
await _sut.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_WhenPreparingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan()
{
// Arrange
MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(failingScanId, LibraryScanJobStatus.Pending);
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
Error error = Error.Failure(description: "Failed to prepare the media library scan");
_mockMediaLibraryScanningService.StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == failingScanId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>())
.Returns(error);
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterRootJob(pendingScanId, pendingRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(failingScanId);
_queue.Writer.TryWrite(pendingScanId);
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
Assert.Equal(1, pendingRootJob.ExecutionCount);
await _sut.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_WhenExecutingAScanIsCancelled_ShouldNotStopProcessingTheNextScan()
{
// Arrange
MediaLibraryScanCompositeId cancelledScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(cancelledScanId, LibraryScanJobStatus.Pending);
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
FakeMediaLibraryScanDiscoveryJob cancelledRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(
onExecute: _ => throw new OperationCanceledException());
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterRootJob(cancelledScanId, cancelledRootJob);
RegisterRootJob(pendingScanId, pendingRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(cancelledScanId);
_queue.Writer.TryWrite(pendingScanId);
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
// Assert
Assert.Equal(1, cancelledRootJob.ExecutionCount);
Assert.Equal(1, pendingRootJob.ExecutionCount);
// A cancelled scan was already reported by its own cancellation event, so no failure is published for it.
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
await _sut.StopAsync(CancellationToken.None);
}
[Fact]
public async Task ExecuteAsync_WhenExecutingAScanFails_ShouldReportTheFailureForThatScanAndProcessTheNextScan()
{
// Arrange
MediaLibraryScanCompositeId failingScanId = _mediaLibraryScanCompositeIdFixture.Create();
MediaLibraryScanCompositeId pendingScanId = _mediaLibraryScanCompositeIdFixture.Create();
RegisterScan(failingScanId, LibraryScanJobStatus.Pending);
RegisterScan(pendingScanId, LibraryScanJobStatus.Pending);
FakeMediaLibraryScanDiscoveryJob failingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create(
onExecute: _ => throw new InvalidOperationException("The scan job payload failed"));
FakeMediaLibraryScanDiscoveryJob pendingRootJob = _mediaLibraryScanDiscoveryJobFixture.Create();
RegisterRootJob(failingScanId, failingRootJob);
RegisterRootJob(pendingScanId, pendingRootJob);
await _sut.StartAsync(CancellationToken.None);
// Act
_queue.Writer.TryWrite(failingScanId);
_queue.Writer.TryWrite(pendingScanId);
await pendingRootJob.ExecutionCompleted.WaitAsync(s_testTimeout);
// Assert
await _mockDomainEventPublisher.Received(1).PublishAsync(
Arg.Is<IDomainEvent>(domainEvent => domainEvent.GetType() == typeof(LibraryScanFailedDomainEvent)
&& ((LibraryScanFailedDomainEvent)domainEvent).MediaLibraryScanCompositeId == failingScanId),
Arg.Any<CancellationToken>());
Assert.Equal(1, pendingRootJob.ExecutionCount);
await _sut.StopAsync(CancellationToken.None);
}
/// <summary>
/// Registers a media library scan with the given status in the mocked repository.
/// </summary>
/// <param name="compositeId">The composite identifier of the scan to register.</param>
/// <param name="status">The status of the media library scan.</param>
/// <returns>The created media library scan entity.</returns>
private LibraryScanEntity RegisterScan(MediaLibraryScanCompositeId compositeId, LibraryScanJobStatus status)
{
LibraryScanEntity scan = _libraryScanEntityFixture.Create(
id: compositeId.ScanId.Value,
userId: compositeId.UserId.Value,
status: status);
_mockLibraryScanRepository
.GetByIdAsync(scan.Id, Arg.Any<bool>(), false, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryScanEntity?>(scan));
return scan;
}
/// <summary>
/// Registers the file system discovery job that the mocked scanning service prepares for a media library scan.
/// </summary>
/// <param name="compositeId">The composite identifier of the scan that owns the job.</param>
/// <param name="rootJob">The root job to return when the scan is prepared.</param>
private void RegisterRootJob(MediaLibraryScanCompositeId compositeId, IMediaLibraryScanDiscoveryJob rootJob)
{
_mockMediaLibraryScanningService.StartScanAsync(
Arg.Is<LibraryScan>(libraryScan => libraryScan.Id.Value == compositeId.ScanId.Value),
Arg.Any<LibraryType>(),
Arg.Any<CancellationToken>())
.Returns(Result.From(rootJob));
}
/// <summary>
/// Disposes the test dependencies.
/// </summary>
public void Dispose()
{
_serviceProvider.Dispose();
}
}
@@ -0,0 +1,279 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
/// <summary>
/// Contains unit tests for the <see cref="BookArtworkService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookArtworkServiceTests
{
private readonly IEnvironmentContext _mockEnvironmentContext;
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IPathService _mockPathService;
private readonly IHttpClientFactory _mockHttpClientFactory;
private readonly IOptions<MediaSettingsDto> _mockMediaSettingsOptions;
private readonly BookArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly PathSegmentFixture _pathSegmentFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceTests"/> class.
/// </summary>
public BookArtworkServiceTests()
{
_mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
_mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
_mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
_mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
_mockPathService = Substitute.For<IPathService>();
_mockPathService.PathSeparator.Returns('\\');
_mockHttpClientFactory = Substitute.For<IHttpClientFactory>();
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
_mockMediaSettingsOptions = Substitute.For<IOptions<MediaSettingsDto>>();
_mockMediaSettingsOptions.Value.Returns(mediaSettings);
_sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(false));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound()
{
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenFileExistenceCheckFails_ShouldReturnTheError()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg");
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>())
.Returns(Error.Failure("FileSystem.Error", "Failed to check the artwork file"));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("FileSystem.Error", result.FirstError.Code);
}
[Fact]
public void DeleteBookArtwork_WhenListingTheCoverFilesFails_ShouldReturnSuccessAndDeleteNothing()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Error.Failure("FileSystem.Error", "Failed to list the artwork files"));
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any<FileSystemPathId>());
}
[Fact]
public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
string libraryName = "Test Library";
string authorName = "Test Author";
string bookTitle = "Test Book";
string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle);
MockArtworkDirectoryStubs(artworkDirectoryPath);
FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg"));
FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json"));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([coverFileId, otherFileId]));
_mockFileProviderService.DeleteFile(Arg.Any<FileSystemPathId>()).Returns(Result.Deleted);
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle);
// Assert
Assert.False(result.IsFailure);
_mockFileProviderService.Received(1).DeleteFile(coverFileId);
_mockFileProviderService.DidNotReceive().DeleteFile(otherFileId);
}
[Fact]
public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError()
{
// Arrange
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(Errors.FileSystemManagement.InvalidPath);
// Act
Result<Deleted> result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title");
// Assert
Assert.True(result.IsFailure);
_mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any<FileSystemPathId>(), true);
}
/// <summary>
/// Stubs the path and file system services so that the artwork is stored into the given directory.
/// </summary>
/// <param name="artworkDirectoryPath">The file system path of the directory into which the artwork is stored.</param>
private void MockArtworkDirectoryStubs(string artworkDirectoryPath)
{
string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media");
string booksPath = Path.Combine(mediaRoot, "books");
_mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot));
_mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath));
_mockPathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.Arg<string>();
return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false));
});
_mockPathService.SanitizeCompositeSegment(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo =>
{
string name = callInfo.ArgAt<string>(0);
string identifier = callInfo.ArgAt<string>(1);
return Result.From(_pathSegmentFixture.Create(name: $"{name}-{identifier}", isDirectory: true, isDrive: false));
});
_mockPathService.CombinePath(Arg.Any<string>(), Arg.Any<string>())
.Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt<string>(0), callInfo.ArgAt<string>(1))));
// Every directory except the artwork directory itself already exists, so that only the final directory is created.
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(callInfo => Result.From(!string.Equals(callInfo.Arg<FileSystemPathId>().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase)));
_mockDirectoryProviderService.CreateDirectory(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>()))));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
}
/// <summary>
/// Builds the file system path of the directory that the artwork of the book is stored into.
/// </summary>
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
/// <param name="bookId">The Id of the book.</param>
/// <param name="libraryName">The name of the media library the book belongs to.</param>
/// <param name="authorName">The name of the author of the book.</param>
/// <param name="bookTitle">The title of the book.</param>
/// <returns>The expected file system path of the book artwork directory.</returns>
private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle)
{
return Path.Combine(
AppContext.BaseDirectory,
"media",
"books",
$"{libraryName}-{libraryId}",
authorName,
$"{bookTitle}-{bookId}");
}
[Fact]
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsNull_ShouldReturnFileNotFound()
{
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", null!, "cover.jpg", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
}
[Fact]
public async Task SaveBookArtworkAsync_WhenUploadedStreamIsEmpty_ShouldReturnFileNotFound()
{
// Arrange
await using MemoryStream emptyStream = new([]);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", emptyStream, "cover.jpg", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SaveBookArtworkAsync_WhenUploadedStreamExceedsTheMaximumSize_ShouldReturnFileTooLarge()
{
// Arrange
await using MemoryStream oversizedStream = new(new byte[(10 * 1024 * 1024) + 1]);
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", oversizedStream, "cover.jpg", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError);
await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,583 @@
#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.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Metadata;
/// <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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: 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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: 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(
includeTitle: false,
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: null,
description: null,
publisher: null,
pageCount: null);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: 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(
includeTitle: false,
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: null,
coverImagePath: null);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeTitle: false,
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: 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(
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
releaseInfo: _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: ReleaseCountry.US));
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
releaseInfo: _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: ReleaseCountry.GB, 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(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry);
Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion);
}
[Fact]
public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Null(result.ReleaseInfo);
}
[Fact]
public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName()
{
// Arrange
BookMetadataDto first = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
genres: [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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(
includeReleaseInfo: false,
includeGenres: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
tags: [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
isbns: [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author)]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
contributors: [_mediaContributorDtoFixture.Create("Author A", MediaContributorRole.Author), _mediaContributorDtoFixture.Create("Translator B", MediaContributorRole.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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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(
includeReleaseInfo: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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", MediaContributorRole.Author)],
ratings: [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)]);
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
// 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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
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", MediaContributorRole.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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeLanguage: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover");
// 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(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
language: _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English"));
BookMetadataDto second = _bookMetadataDtoFixture.Create(
includeReleaseInfo: false,
includeGenres: false,
includeTags: false,
includeFormat: false,
includeVolumeNumber: false,
title: "Title",
coverImagePath: "First Cover",
language: _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch"));
// Act
BookMetadataDto result = MetadataAggregator.Merge(first, second);
// Assert
Assert.Equal("en", result.Language!.LanguageCode);
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReaderEnablementCache"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReaderEnablementCacheTests
{
private readonly BookReaderEnablementCache _sut = new();
[Fact]
public void Get_WhenNothingIsCached_ShouldReturnNull()
{
// Act
bool? result = _sut.Get(Guid.NewGuid(), Guid.NewGuid());
// Assert
Assert.Null(result);
}
[Theory]
[InlineData(true)] // Reader enabled.
[InlineData(false)] // Reader disabled.
public void Set_WhenCalled_ThenGetShouldReturnTheCachedValue(bool isEnabled)
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
// Act
_sut.Set(libraryId, pluginId, isEnabled);
// Assert
Assert.Equal(isEnabled, _sut.Get(libraryId, pluginId));
}
[Fact]
public void Invalidate_WhenCalled_ShouldRemoveOnlyTheGivenLibraryAndPluginPair()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
_sut.Set(libraryId, firstPluginId, isEnabled: true);
_sut.Set(libraryId, secondPluginId, isEnabled: false);
// Act
_sut.Invalidate(libraryId, firstPluginId);
// Assert
Assert.Null(_sut.Get(libraryId, firstPluginId));
Assert.False(_sut.Get(libraryId, secondPluginId));
}
[Fact]
public void InvalidateLibrary_WhenCalled_ShouldRemoveEveryEntryOfTheLibraryAndKeepTheOthers()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid otherLibraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
Guid otherPluginId = Guid.NewGuid();
_sut.Set(libraryId, pluginId, isEnabled: true);
_sut.Set(libraryId, otherPluginId, isEnabled: false);
_sut.Set(otherLibraryId, pluginId, isEnabled: true);
// Act
_sut.InvalidateLibrary(libraryId);
// Assert
Assert.Null(_sut.Get(libraryId, pluginId));
Assert.Null(_sut.Get(libraryId, otherPluginId));
Assert.True(_sut.Get(otherLibraryId, pluginId));
}
[Fact]
public void InvalidatePlugin_WhenCalled_ShouldRemoveEveryEntryOfThePluginAndKeepTheOthers()
{
// Arrange
Guid libraryId = Guid.NewGuid();
Guid otherLibraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
Guid otherPluginId = Guid.NewGuid();
_sut.Set(libraryId, pluginId, isEnabled: true);
_sut.Set(otherLibraryId, pluginId, isEnabled: false);
_sut.Set(libraryId, otherPluginId, isEnabled: true);
// Act
_sut.InvalidatePlugin(pluginId);
// Assert
Assert.Null(_sut.Get(libraryId, pluginId));
Assert.Null(_sut.Get(otherLibraryId, pluginId));
Assert.True(_sut.Get(libraryId, otherPluginId));
}
}
@@ -0,0 +1,146 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Reading;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReaderRegistry"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReaderRegistryTests
{
private readonly IPluginManager _mockPluginManager;
private readonly IServiceProvider _serviceProvider;
private readonly BookReaderRegistry _sut;
private readonly Guid _pluginId = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="BookReaderRegistryTests"/> class.
/// </summary>
public BookReaderRegistryTests()
{
_mockPluginManager = Substitute.For<IPluginManager>();
_serviceProvider = new ServiceCollection().BuildServiceProvider();
_sut = new BookReaderRegistry(_mockPluginManager, _serviceProvider);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenReadersAreRegistered_ShouldReturnExtensionsKeyedByPluginId()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader reader = CreateReader(".epub", ".EPUB");
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
IReadOnlyList<string> extensions = Assert.Single(result.Values);
Assert.Equal([".epub"], extensions);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenReaderHasNoUsableExtensions_ShouldSkipThePlugin()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader reader = CreateReader(string.Empty);
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceProvider serviceProvider = BuildServiceProviderWithReaders(plugin.Id, reader);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenNoReadersAreRegistered_ShouldReturnEmptyDictionary()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = _sut.GetSupportedExtensionsByPluginId();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetSupportedExtensionsByPluginId_WhenMultipleReadersOfOnePlugin_ShouldMergeAndDistinctExtensions()
{
// Arrange
IPlugin plugin = CreatePlugin(_pluginId, "Test Plugin");
IBookReader firstReader = CreateReader(".pdf");
IBookReader secondReader = CreateReader(".pdf", ".epub");
_mockPluginManager.GetPlugins().Returns([plugin]);
ServiceCollection services = new();
services.AddKeyedSingleton(plugin.Id, firstReader);
services.AddKeyedSingleton(plugin.Id, secondReader);
ServiceProvider serviceProvider = services.BuildServiceProvider();
// Act
IReadOnlyDictionary<Guid, IReadOnlyList<string>> result = new BookReaderRegistry(_mockPluginManager, serviceProvider).GetSupportedExtensionsByPluginId();
// Assert
IReadOnlyList<string> extensions = Assert.Single(result.Values);
Assert.Equal([".epub", ".pdf"], extensions);
}
/// <summary>
/// Creates a mocked plugin with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin.</param>
/// <param name="name">The name of the plugin.</param>
/// <returns>The created plugin mock.</returns>
private static IPlugin CreatePlugin(Guid id, string name)
{
IPlugin plugin = Substitute.For<IPlugin>();
plugin.Id.Returns(id);
plugin.Name.Returns(name);
return plugin;
}
/// <summary>
/// Creates a mocked book reader with the provided extensions.
/// </summary>
/// <param name="extensions">The supported extensions of the reader.</param>
/// <returns>The created reader mock.</returns>
private static IBookReader CreateReader(params string[] extensions)
{
IBookReader reader = Substitute.For<IBookReader>();
reader.SupportedExtensions.Returns(extensions);
reader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
return reader;
}
/// <summary>
/// Builds a service provider in which the provided readers are registered as keyed services of the plugin.
/// </summary>
/// <param name="pluginId">The Id of the plugin providing the readers.</param>
/// <param name="readers">The readers to register.</param>
/// <returns>The built service provider.</returns>
private static ServiceProvider BuildServiceProviderWithReaders(Guid pluginId, params IBookReader[] readers)
{
ServiceCollection services = new();
foreach (IBookReader reader in readers)
services.AddKeyedSingleton<IBookReader>(pluginId, reader);
return services.BuildServiceProvider();
}
}
@@ -0,0 +1,188 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Reading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="BookReadingService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookReadingServiceTests
{
private readonly IPluginManager _mockPluginManager;
private readonly IPlugin _mockPlugin;
private readonly IBookReader _mockReader;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryBookReaderConfigurationRepository _mockConfigurationRepository;
private readonly IServiceProvider _serviceProvider;
private readonly BookReadingService _sut;
private readonly BookReaderEnablementCache _enablementCache = new();
private readonly Guid _pluginId = Guid.NewGuid();
private readonly Guid _bookId = Guid.NewGuid();
private readonly Guid _libraryId = Guid.NewGuid();
private readonly string _bookPath;
private readonly LibraryBookReaderConfigurationEntityFixture _libraryBookReaderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookReadingServiceTests"/> class.
/// </summary>
public BookReadingServiceTests()
{
_mockReader = Substitute.For<IBookReader>();
_mockReader.SupportedExtensions.Returns([".epub"]);
_mockReader.SupportedLibraryTypes.Returns([LibraryType.EBook]);
_mockPlugin = Substitute.For<IPlugin>();
_mockPlugin.Id.Returns(_pluginId);
_mockPlugin.Name.Returns("Test Reader");
_mockPluginManager = Substitute.For<IPluginManager>();
_mockPluginManager.GetPlugins().Returns([_mockPlugin]);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockConfigurationRepository = Substitute.For<ILibraryBookReaderConfigurationRepository>();
_mockUnitOfWork.LibraryBookReaderConfigurationRepository.Returns(_mockConfigurationRepository);
LibraryBookReaderConfigurationEntity enabledConfiguration = _libraryBookReaderConfigurationEntityFixture.Create(libraryId: _libraryId, pluginId: _pluginId, isEnabled: true);
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(enabledConfiguration));
ServiceCollection services = new();
services.AddKeyedSingleton(_pluginId, _mockReader);
services.AddSingleton(_mockUnitOfWork);
_serviceProvider = services.BuildServiceProvider();
IServiceScopeFactory serviceScopeFactory = _serviceProvider.GetRequiredService<IServiceScopeFactory>();
// The resolution and enablement guards under test stop before the book file is probed, so no real file is needed.
_bookPath = $"lumina-test-book-{Guid.NewGuid():N}.epub";
_sut = new BookReadingService(_serviceProvider, _mockPluginManager, _enablementCache, serviceScopeFactory, Substitute.For<ILogger<BookReadingService>>());
}
[Fact]
public async Task GetManifestAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenReaderIsDisabledForTheLibrary_ShouldReturnReaderDisabledError()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.ReaderDisabled, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetManifestAsync_WhenConfigurationsReadFails_ShouldReturnError()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Reading.Error", "Failed to read the configuration"));
// Act
Result<ReadingManifestResponse> result = await _sut.GetManifestAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, shouldRenderPdfAsImages: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Reading.Error", result.FirstError.Code);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetSectionAsync_WhenNoReaderSupportsTheFormat_ShouldReturnNoReaderAvailableError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingSectionDto> result = await _sut.GetSectionAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, "section-1", shouldRenderPdfAsImages: false, shouldPreserveStyles: false, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Reading.NoReaderAvailable, result.FirstError);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAvailabilityAsync_WhenReaderIsAvailableAndEnabled_ShouldReportAvailable()
{
// Arrange
CancellationToken cancellationToken = CancellationToken.None;
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, cancellationToken);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsAvailable);
Assert.Null(result.Value.ErrorCode);
await _mockReader.DidNotReceive().OpenAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAvailabilityAsync_WhenNoReaderSupportsTheFormat_ShouldReportUnavailableWithNoReaderAvailable()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsAvailable);
Assert.Equal(nameof(Errors.Reading.NoReaderAvailable), result.Value.ErrorCode);
}
[Fact]
public async Task GetAvailabilityAsync_WhenReaderIsDisabled_ShouldReportUnavailableWithReaderDisabled()
{
// Arrange
_mockConfigurationRepository.GetByLibraryAndPluginIdAsync(_libraryId, _pluginId, Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryBookReaderConfigurationEntity?>(null));
// Act
Result<ReadingAvailabilityResponse> result = await _sut.GetAvailabilityAsync(_bookId, _libraryId, _bookPath, LibraryType.EBook, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(result.Value.IsAvailable);
Assert.Equal(nameof(Errors.Reading.ReaderDisabled), result.Value.ErrorCode);
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingCachePaths"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingCachePathsTests
{
[Fact]
public void GetRootDirectory_WhenCalled_ShouldReturnBaseDirectoryWithReadingCacheDirectoryName()
{
// Act
string result = ReadingCachePaths.GetRootDirectory();
// Assert
Assert.Equal(Path.Combine(AppContext.BaseDirectory, ReadingCachePaths.DIRECTORY_NAME), result);
}
[Fact]
public void DirectoryName_WhenAccessed_ShouldReturnReadingCache()
{
// Assert
Assert.Equal("reading-cache", ReadingCachePaths.DIRECTORY_NAME);
}
}
@@ -0,0 +1,159 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
/// <summary>
/// Contains unit tests for the <see cref="ReadingContentSanitizer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReadingContentSanitizerTests
{
[Fact]
public void Sanitize_WhenHtmlContainsScript_ShouldStripTheScript()
{
// Arrange
string html = "<section><p>Hello</p><script>alert('xss')</script></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsInlineEventHandler_ShouldStripTheHandler()
{
// Arrange
string html = "<p onclick=\"alert('xss')\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsJavascriptUrl_ShouldStripTheReference()
{
// Arrange
string html = "<a href=\"javascript:alert('xss')\">Link</a>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("javascript", result, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Sanitize_WhenHtmlContainsIframe_ShouldStripTheIframe()
{
// Arrange
string html = "<iframe src=\"https://evil.example\"></iframe><p>Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("iframe", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsDataLuminaResourceMarker_ShouldKeepTheMarker()
{
// Arrange
string html = $"<img {ReadingContentSanitizer.RESOURCE_ATTRIBUTE}=\"page:1\" alt=\"Page\" />";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.Contains(ReadingContentSanitizer.RESOURCE_ATTRIBUTE, result, StringComparison.Ordinal);
Assert.Contains("page:1", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenHtmlContainsPlainContent_ShouldKeepTheContent()
{
// Arrange
string html = "<section><h1>Chapter 1</h1><p>Some text.</p></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.Contains("Chapter 1", result, StringComparison.Ordinal);
Assert.Contains("Some text.", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenShouldPreserveStylesIsTrue_ShouldKeepTheStyleAttribute()
{
// Arrange
string html = "<p style=\"color:red\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: true);
// Assert
Assert.Contains("style", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Fact]
public void Sanitize_WhenShouldPreserveStylesIsFalse_ShouldStripTheStyleAttribute()
{
// Arrange
string html = "<p style=\"color:red\">Hello</p>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles: false);
// Assert
Assert.DoesNotContain("style", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("color:red", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
}
[Theory]
[InlineData(true)] // Preserve styles.
[InlineData(false)] // Strip styles.
public void Sanitize_WhenHtmlContainsActiveContent_ShouldStripItRegardlessOfTheStylePreference(bool shouldPreserveStyles)
{
// Arrange
string html = "<section><p style=\"color:red\">Hello</p><script>alert('xss')</script><p onclick=\"alert('xss')\">World</p></section>";
// Act
string result = ReadingContentSanitizer.Sanitize(html, shouldPreserveStyles);
// Assert
Assert.DoesNotContain("script", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("alert", result, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("onclick", result, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Hello", result, StringComparison.Ordinal);
Assert.Contains("World", result, StringComparison.Ordinal);
}
[Theory]
[InlineData(null)] // Null input.
[InlineData("")] // Empty input.
[InlineData(" ")] // Whitespace input.
public void Sanitize_WhenInputIsBlank_ShouldReturnEmptyString(string? html)
{
// Act
string result = ReadingContentSanitizer.Sanitize(html!, shouldPreserveStyles: false);
// Assert
Assert.Equal(string.Empty, result);
}
}
@@ -0,0 +1,324 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Infrastructure.Common.Models.DTO.Plugins;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginDetectionSyncJob"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginDetectionSyncJobTests
{
private readonly IServiceScopeFactory _mockServiceScopeFactory;
private readonly IServiceScope _mockServiceScope;
private readonly IServiceProvider _mockServiceProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore;
private readonly IPluginManager _mockPluginManager;
private readonly ILogger<PluginDetectionSyncJob> _mockLogger;
private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture;
private readonly PluginEntityFixture _pluginEntityFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly PaginatedResultDtoFixture<PluginEntity> _pluginPaginatedResultDtoFixture = new();
private readonly PaginatedResultDtoFixture<LibraryEntity> _libraryPaginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PluginDetectionSyncJobTests"/> class.
/// </summary>
public PluginDetectionSyncJobTests()
{
_mockServiceScopeFactory = Substitute.For<IServiceScopeFactory>();
_mockServiceScope = Substitute.For<IServiceScope>();
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope);
_mockServiceScope.ServiceProvider.Returns(_mockServiceProvider);
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockProviderConfigurationStore = Substitute.For<IMediaLibraryProviderConfigurationStore>();
_mockProviderConfigurationStore.RemoveProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork);
_mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore);
_mockPluginManager = Substitute.For<IPluginManager>();
_mockLogger = Substitute.For<ILogger<PluginDetectionSyncJob>>();
_pluginLoadErrorDtoFixture = new PluginLoadErrorDtoFixture();
}
[Fact]
public async Task StartAsync_WhenPluginsAreLoaded_ShouldPersistTheDetectionOfAllPlugins()
{
// Arrange
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin", new Version(1, 2, 3));
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin", new Version(2, 0, 0));
_mockPluginManager.GetPlugins().Returns([firstPlugin, secondPlugin]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == firstPlugin.Id
&& plugin.Name == firstPlugin.Name
&& plugin.Author == firstPlugin.Author
&& plugin.Version == firstPlugin.Version.ToString()
&& plugin.Description == firstPlugin.Description
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
Arg.Any<CancellationToken>());
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == secondPlugin.Id
&& plugin.Name == secondPlugin.Name
&& plugin.LoadStatus == PluginLoadStatus.Loaded),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0));
IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]);
_mockPluginRepository.UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == failingPlugin.Id),
Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to persist the plugin"));
_mockPluginRepository.UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id),
Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is<PluginEntity>(plugin => plugin.Id == successfulPlugin.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Error,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.DidNotReceiveWithAnyArgs().UpsertAsync(default!, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPluginFailsToLoad_ShouldPersistFailedPluginWithError()
{
// Arrange
_mockPluginManager.GetPlugins().Returns([]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create(
assemblyName: "BrokenPlugin",
errorMessage: "Failed to load plugin assembly 'BrokenPlugin.dll': bad image");
PluginDetectionSyncJob sut = CreateSut([loadError]);
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName)
&& plugin.Name == loadError.AssemblyName
&& plugin.LoadStatus == PluginLoadStatus.FailedToLoad
&& plugin.LoadError == loadError.ErrorMessage),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPreviouslyDetectedPluginIsNoLongerPresent_ShouldRemoveItsRow()
{
// Arrange
IPlugin loadedPlugin = CreatePlugin(Guid.NewGuid(), "Loaded Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([loadedPlugin]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginEntity loadedPluginRow = _pluginEntityFixture.Create(id: loadedPlugin.Id, name: loadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded);
PluginEntity stalePluginRow = _pluginEntityFixture.Create(name: "Stale Plugin", loadStatus: PluginLoadStatus.Loaded);
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_pluginPaginatedResultDtoFixture.Create(data: [loadedPluginRow, stalePluginRow], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockPluginRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).DeleteByIdAsync(stalePluginRow.Id, Arg.Any<CancellationToken>());
await _mockPluginRepository.DidNotReceive().DeleteByIdAsync(loadedPluginRow.Id, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.Received(1).RemoveProviderConfigurationsAsync(stalePluginRow.Id, Arg.Any<CancellationToken>());
await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsAsync(loadedPluginRow.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenMediaLibrariesExist_ShouldEnsureTheirProviderConfigurations()
{
// Arrange
IPlugin loadedPlugin = CreatePlugin(Guid.NewGuid(), "Loaded Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([loadedPlugin]);
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book);
_mockLibraryRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryPaginatedResultDtoFixture.Create(data: [bookLibrary], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
PluginDetectionSyncJob sut = CreateSut();
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
// A single ensure covers the metadata, artwork and book reader configurations, since a second one before the save would stage duplicates.
await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task StartAsync_WhenPreviouslyLoadedPluginNowFailsToLoad_ShouldReplaceItWithASingleFailedRow()
{
// Arrange
IPlugin previouslyLoadedPlugin = CreatePlugin(Guid.NewGuid(), "My Plugin", new Version(1, 0, 0));
_mockPluginManager.GetPlugins().Returns([]); // The plugin assembly now fails to load.
_mockPluginRepository.UpsertAsync(Arg.Any<PluginEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.From(Result.Updated));
PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create(
assemblyName: "MyPlugin",
errorMessage: "Failed to load plugin assembly 'MyPlugin.dll': unexpected error");
PluginEntity staleLoadedRow = _pluginEntityFixture.Create(id: previouslyLoadedPlugin.Id, name: previouslyLoadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded);
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From(_pluginPaginatedResultDtoFixture.Create(data: [staleLoadedRow], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any<CancellationToken>())
.Returns(Result.Deleted);
PluginDetectionSyncJob sut = CreateSut([loadError]);
// Act
await StartAndWaitForExecutionAsync(sut);
// Assert
await _mockPluginRepository.Received(1).UpsertAsync(
Arg.Is<PluginEntity>(plugin => plugin.Id == DeriveExpectedId(loadError.AssemblyName)
&& plugin.Name == loadError.AssemblyName
&& plugin.LoadStatus == PluginLoadStatus.FailedToLoad
&& plugin.LoadError == loadError.ErrorMessage),
Arg.Any<CancellationToken>());
await _mockPluginRepository.Received(1).DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
/// <summary>
/// Invokes the protected <see cref="BackgroundService.ExecuteAsync"/> of the job and awaits its completion.
/// </summary>
/// <param name="sut">The job to execute.</param>
private static async Task StartAndWaitForExecutionAsync(PluginDetectionSyncJob sut)
{
MethodInfo executeAsyncMethod = typeof(PluginDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!;
await executingTask;
}
/// <summary>
/// Creates the system under test wired to the mocked dependencies.
/// </summary>
/// <param name="loadErrors">The plugin load errors to feed to the job, when any.</param>
/// <returns>The created job instance.</returns>
private PluginDetectionSyncJob CreateSut(IReadOnlyList<PluginLoadErrorDto>? loadErrors = null)
{
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], _mockLogger);
}
/// <summary>
/// Creates a mocked plugin with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin.</param>
/// <param name="name">The name of the plugin.</param>
/// <param name="version">The version of the plugin.</param>
/// <returns>The created plugin mock.</returns>
private static IPlugin CreatePlugin(Guid id, string name, Version version)
{
IPlugin plugin = Substitute.For<IPlugin>();
plugin.Id.Returns(id);
plugin.Name.Returns(name);
plugin.Author.Returns("Test Author");
plugin.Version.Returns(version);
plugin.Description.Returns("Test plugin description");
return plugin;
}
/// <summary>
/// Derives the stable plugin Id expected for a failing plugin assembly, mirroring the detection job logic.
/// </summary>
/// <param name="assemblyName">The file name of the plugin assembly, without its extension.</param>
/// <returns>The derived plugin identifier.</returns>
private static Guid DeriveExpectedId(string assemblyName)
{
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName));
return new Guid([.. hash.Take(16)]);
}
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginInstaller"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginInstallerTests
{
private readonly PluginInstaller _sut;
private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PluginInstallerTests"/> class.
/// </summary>
public PluginInstallerTests()
{
ILogger<PluginInstaller> mockLogger = Substitute.For<ILogger<PluginInstaller>>();
IOptions<PluginsSettingsDto> mockOptions = Substitute.For<IOptions<PluginsSettingsDto>>();
mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: $".test-plugins-{Guid.NewGuid():N}"));
_sut = new PluginInstaller(mockOptions, mockLogger);
}
[Fact]
public async Task InstallAsync_WhenUploadingUnsupportedFileType_ShouldReturnError()
{
// Arrange
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
// Act
Result<Success> result = await _sut.InstallAsync(stream, "plugin.txt", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.UnsupportedPluginFileType, result.FirstError);
}
[Fact]
public async Task InstallAsync_WhenUploadingCorruptZip_ShouldReturnNotReadableError()
{
// Arrange
await using MemoryStream stream = new([.. new byte[] { 1, 2, 3, 4 }]);
// Act
Result<Success> result = await _sut.InstallAsync(stream, "plugin.zip", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Plugins.PluginArchiveNotReadable, result.FirstError);
}
}
@@ -0,0 +1,89 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Plugins;
using Lumina.Plugins.Contracts.Core.Plugins;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginManager"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginManagerTests
{
[Fact]
public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins()
{
// Arrange
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin");
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin");
PluginManager sut = new([firstPlugin, secondPlugin], []);
// Act
IReadOnlyList<IPlugin> result = sut.GetPlugins();
// Assert
Assert.Equal(2, result.Count);
Assert.Contains(firstPlugin, result);
Assert.Contains(secondPlugin, result);
}
[Fact]
public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList()
{
// Arrange
PluginManager sut = new([], []);
// Act
IReadOnlyList<IPlugin> result = sut.GetPlugins();
// Assert
Assert.Empty(result);
}
[Fact]
public void GetPlugin_WhenPluginWithIdWasLoaded_ShouldReturnThePlugin()
{
// Arrange
Guid pluginId = Guid.NewGuid();
IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin");
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], []);
// Act
IPlugin? result = sut.GetPlugin(pluginId);
// Assert
Assert.Same(expectedPlugin, result);
}
[Fact]
public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull()
{
// Arrange
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], []);
// Act
IPlugin? result = sut.GetPlugin(Guid.NewGuid());
// Assert
Assert.Null(result);
}
/// <summary>
/// Creates a mocked plugin with the provided identity.
/// </summary>
/// <param name="id">The Id of the plugin.</param>
/// <param name="name">The name of the plugin.</param>
/// <returns>The created plugin mock.</returns>
private static IPlugin CreatePlugin(Guid id, string name)
{
IPlugin plugin = Substitute.For<IPlugin>();
plugin.Id.Returns(id);
plugin.Name.Returns(name);
return plugin;
}
}
@@ -0,0 +1,117 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Plugins;
using Lumina.Application.Common.DataAccess.Repositories.Plugins;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Domain.Common.Primitives;
using Lumina.Infrastructure.Core.Plugins;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Plugins;
/// <summary>
/// Contains unit tests for the <see cref="PluginSettingsStore"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PluginSettingsStoreTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IPluginRepository _mockPluginRepository;
private readonly ILogger<PluginSettingsStore> _mockLogger;
private readonly PluginSettingsStore _sut;
private readonly PluginEntityFixture _pluginEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="PluginSettingsStoreTests"/> class.
/// </summary>
public PluginSettingsStoreTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockPluginRepository = Substitute.For<IPluginRepository>();
_mockLogger = Substitute.For<ILogger<PluginSettingsStore>>();
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
_sut = new PluginSettingsStore(_mockUnitOfWork, _mockLogger);
}
[Fact]
public async Task GetSettingsAsync_WhenPluginHasPersistedSettings_ShouldReturnDeserializedSettings()
{
// Arrange
Guid pluginId = Guid.NewGuid();
Dictionary<string, string> expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" };
PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, settingsJson: JsonSerializer.Serialize(expectedSettings));
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<PluginEntity?>(pluginEntity));
// Act
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(expectedSettings, result);
}
[Fact]
public async Task GetSettingsAsync_WhenPluginHasNoPersistedSettings_ShouldReturnNull()
{
// Arrange
Guid pluginId = Guid.NewGuid();
PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, includeSettingsJson: false);
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<PluginEntity?>(pluginEntity));
// Act
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetSettingsAsync_WhenPluginDoesNotExist_ShouldReturnNull()
{
// Arrange
Guid pluginId = Guid.NewGuid();
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<PluginEntity?>(null));
// Act
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
// Assert
Assert.Null(result);
}
[Fact]
public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
Guid pluginId = Guid.NewGuid();
_mockPluginRepository.GetByIdAsync(pluginId, cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin"));
// Act
IReadOnlyDictionary<string, string>? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None);
// Assert
Assert.Null(result);
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to read the settings of the plugin")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
}
@@ -0,0 +1,218 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate.ValueObjects;
using Lumina.Infrastructure.Core.Scheduling.Execution;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobRuntimeRegistry"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobRuntimeRegistryTests
{
private readonly ScheduledJobRuntimeRegistry _sut = new();
private readonly ScheduledJobIdFixture _scheduledJobIdFixture = new();
[Fact]
public void TryStartCycle_WhenNoCycleIsRunning_ShouldReturnTrue()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
// Act
bool result = _sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(result);
}
[Fact]
public void TryStartCycle_WhenCycleIsAlreadyRunning_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource firstCancellationTokenSource = new();
using CancellationTokenSource secondCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, firstCancellationTokenSource);
// Act
bool result = _sut.TryStartCycle(scheduledJobId, secondCancellationTokenSource);
// Assert
Assert.False(result);
}
[Fact]
public void StopCycle_WhenCycleIsRunning_ShouldCancelTheCycleAndAllowRestartingIt()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
_sut.StopCycle(scheduledJobId);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
using CancellationTokenSource restartedCycleCancellationTokenSource = new();
Assert.True(_sut.TryStartCycle(scheduledJobId, restartedCycleCancellationTokenSource));
}
[Fact]
public void StopCycle_WhenNoCycleIsRunning_ShouldNotThrow()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
// Act
_sut.StopCycle(scheduledJobId);
// Assert
Assert.True(true);
}
[Fact]
public void TryAcquireRunSlot_WhenNoExecutionIsRunning_ShouldReturnTrueAndThenFalseWhileHeld()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
// Act
bool firstAcquire = _sut.TryAcquireRunSlot(scheduledJobId);
bool secondAcquire = _sut.TryAcquireRunSlot(scheduledJobId);
// Assert
Assert.True(firstAcquire);
Assert.False(secondAcquire);
}
[Fact]
public void ReleaseRunSlot_WhenSlotWasAcquired_ShouldAllowAcquiringItAgain()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
_sut.TryAcquireRunSlot(scheduledJobId);
// Act
_sut.ReleaseRunSlot(scheduledJobId);
// Assert
Assert.True(_sut.TryAcquireRunSlot(scheduledJobId));
}
[Fact]
public void TryAcquireRunSlot_AfterReleasingTheSlot_ShouldReturnTrue()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
_sut.TryAcquireRunSlot(scheduledJobId);
_sut.ReleaseRunSlot(scheduledJobId);
// Act
bool result = _sut.TryAcquireRunSlot(scheduledJobId);
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenCycleIsRunning_ShouldReturnTrue()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.True(result);
}
[Fact]
public void HasActiveCycle_WhenNoCycleIsRunning_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void HasActiveCycle_AfterTheCycleWasStopped_ShouldReturnFalse()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
// Act
bool result = _sut.HasActiveCycle(scheduledJobId);
// Assert
Assert.False(result);
}
[Fact]
public void EndCycle_WhenCalledWithTheOwnedTokenSource_ShouldCancelItAndClearTheCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, cycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenTheCycleWasReplacedByANewerOne_ShouldNotCancelTheNewerCycle()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource oldCycleCancellationTokenSource = new();
using CancellationTokenSource newCycleCancellationTokenSource = new();
_sut.TryStartCycle(scheduledJobId, oldCycleCancellationTokenSource);
_sut.StopCycle(scheduledJobId);
_sut.TryStartCycle(scheduledJobId, newCycleCancellationTokenSource);
// Act
_sut.EndCycle(scheduledJobId, oldCycleCancellationTokenSource);
// Assert
Assert.True(oldCycleCancellationTokenSource.IsCancellationRequested);
Assert.False(newCycleCancellationTokenSource.IsCancellationRequested);
Assert.True(_sut.HasActiveCycle(scheduledJobId));
}
[Fact]
public void EndCycle_WhenNoCycleIsRegistered_ShouldStillCancelTheOwnedTokenSource()
{
// Arrange
ScheduledJobId scheduledJobId = _scheduledJobIdFixture.Create();
using CancellationTokenSource cycleCancellationTokenSource = new();
// Act
_sut.EndCycle(scheduledJobId, cycleCancellationTokenSource);
// Assert
Assert.True(cycleCancellationTokenSource.IsCancellationRequested);
Assert.False(_sut.HasActiveCycle(scheduledJobId));
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Events;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledTaskExecutorFactory"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledTaskExecutorFactoryTests
{
private readonly IServiceProvider _mockServiceProvider;
private readonly MediaLibraryScanTaskExecutor _mockMediaLibraryScanTaskExecutor;
private readonly TemporaryFilesCleanupTaskExecutor _mockTemporaryFilesCleanupTaskExecutor;
private readonly RepairThemesTaskExecutor _mockRepairThemesTaskExecutor;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _mockCleanScheduledJobExecutionHistoryTaskExecutor;
private readonly TechnicalDataCleanupTaskExecutor _mockTechnicalDataCleanupTaskExecutor;
private readonly ScheduledTaskExecutorFactory _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledTaskExecutorFactoryTests"/> class.
/// </summary>
public ScheduledTaskExecutorFactoryTests()
{
_mockServiceProvider = Substitute.For<IServiceProvider>();
_mockMediaLibraryScanTaskExecutor = Substitute.For<MediaLibraryScanTaskExecutor>(
Substitute.For<IDomainEventPublisher>(),
Substitute.For<ILogger<MediaLibraryScanTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockTemporaryFilesCleanupTaskExecutor = Substitute.For<TemporaryFilesCleanupTaskExecutor>(
Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>());
_mockRepairThemesTaskExecutor = Substitute.For<RepairThemesTaskExecutor>(
Substitute.For<Lumina.Application.Common.Infrastructure.Themes.IThemeService>(),
Substitute.For<ILogger<RepairThemesTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockCleanScheduledJobExecutionHistoryTaskExecutor = Substitute.For<CleanScheduledJobExecutionHistoryTaskExecutor>(
Substitute.For<IDateTimeProvider>(),
Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockTechnicalDataCleanupTaskExecutor = Substitute.For<TechnicalDataCleanupTaskExecutor>(
Substitute.For<ILogger<TechnicalDataCleanupTaskExecutor>>(),
Substitute.For<IUnitOfWork>());
_mockServiceProvider.GetService(typeof(MediaLibraryScanTaskExecutor)).Returns(_mockMediaLibraryScanTaskExecutor);
_mockServiceProvider.GetService(typeof(TemporaryFilesCleanupTaskExecutor)).Returns(_mockTemporaryFilesCleanupTaskExecutor);
_mockServiceProvider.GetService(typeof(RepairThemesTaskExecutor)).Returns(_mockRepairThemesTaskExecutor);
_mockServiceProvider.GetService(typeof(CleanScheduledJobExecutionHistoryTaskExecutor)).Returns(_mockCleanScheduledJobExecutionHistoryTaskExecutor);
_mockServiceProvider.GetService(typeof(TechnicalDataCleanupTaskExecutor)).Returns(_mockTechnicalDataCleanupTaskExecutor);
_sut = new ScheduledTaskExecutorFactory(_mockServiceProvider);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsScanMediaLibraries_ShouldReturnMediaLibraryScanTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.ScanMediaLibraries);
// Assert
Assert.Same(_mockMediaLibraryScanTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsCleanTemporaryFiles_ShouldReturnTemporaryFilesCleanupTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanTemporaryFiles);
// Assert
Assert.Same(_mockTemporaryFilesCleanupTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsRepairThemes_ShouldReturnRepairThemesTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.RepairThemes);
// Assert
Assert.Same(_mockRepairThemesTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsCleanScheduledJobExecutionHistory_ShouldReturnCleanScheduledJobExecutionHistoryTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.CleanScheduledJobExecutionHistory);
// Assert
Assert.Same(_mockCleanScheduledJobExecutionHistoryTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsTechnicalDataCleanup_ShouldReturnTechnicalDataCleanupTaskExecutor()
{
// Act
IScheduledTaskExecutor result = _sut.CreateExecutor(ScheduledTaskType.TechnicalDataCleanup);
// Assert
Assert.Same(_mockTechnicalDataCleanupTaskExecutor, result);
}
[Fact]
public void CreateExecutor_WhenTaskTypeIsUnsupported_ShouldThrowArgumentException()
{
// Act
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.CreateExecutor((ScheduledTaskType)999));
// Assert
Assert.Contains("Unsupported task type", exception.Message);
Assert.Equal("taskType", exception.ParamName);
}
}
@@ -0,0 +1,79 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.Scheduling;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Time;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="CleanScheduledJobExecutionHistoryTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CleanScheduledJobExecutionHistoryTaskExecutorTests
{
private readonly IDateTimeProvider _mockDateTimeProvider;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IScheduledJobExecutionRepository _mockScheduledJobExecutionRepository;
private readonly CleanScheduledJobExecutionHistoryTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly DateTime _fixedUtcNow = DateTime.UtcNow;
/// <summary>
/// Initializes a new instance of the <see cref="CleanScheduledJobExecutionHistoryTaskExecutorTests"/> class.
/// </summary>
public CleanScheduledJobExecutionHistoryTaskExecutorTests()
{
_mockDateTimeProvider = Substitute.For<IDateTimeProvider>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockScheduledJobExecutionRepository = Substitute.For<IScheduledJobExecutionRepository>();
_mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow);
_mockUnitOfWork.ScheduledJobExecutionRepository.Returns(_mockScheduledJobExecutionRepository);
ILogger<CleanScheduledJobExecutionHistoryTaskExecutor> logger = Substitute.For<ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>>();
_sut = new CleanScheduledJobExecutionHistoryTaskExecutor(_mockDateTimeProvider, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldDeleteTheExecutionsOlderThanAMonth()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(Result.Success);
DateTime expectedCutoff = _fixedUtcNow.AddMonths(-1);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockScheduledJobExecutionRepository.Received(1).DeleteOlderThanAsync(Arg.Is<DateTime>(cutoff => cutoff == expectedCutoff), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheDeletionFails_ShouldReturnTheError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.CleanScheduledJobExecutionHistory);
Error expectedError = Error.Failure("Database.Error", "Failed to delete the old executions");
_mockScheduledJobExecutionRepository.DeleteOlderThanAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>()).Returns(expectedError);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
}
@@ -0,0 +1,172 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="MediaLibraryScanTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaLibraryScanTaskExecutorTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryRepository _mockLibraryRepository;
private readonly IDomainEventPublisher _mockDomainEventPublisher;
private readonly MediaLibraryScanTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="MediaLibraryScanTaskExecutorTests"/> class.
/// </summary>
public MediaLibraryScanTaskExecutorTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([]));
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockDomainEventPublisher = Substitute.For<IDomainEventPublisher>();
_sut = new MediaLibraryScanTaskExecutor(_mockDomainEventPublisher, Substitute.For<ILogger<MediaLibraryScanTaskExecutor>>(), _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenNoLibrariesAreEnabled_ShouldReturnSuccessWithoutPublishingEvents()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenGetAllEnabledAndUnlockedLibrariesFails_ShouldReturnError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
Error error = Error.Failure("Database.Error", "Failed to get the enabled libraries");
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenGetPastMonthScansFails_ShouldReturnError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
Error error = Error.Failure("Database.Error", "Failed to get the past month scans");
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
}
[Fact]
public async Task ExecutePayloadAsync_WhenALibraryIsAlreadyBeingScanned_ShouldSkipThatLibrary()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: library.Id, status: LibraryScanJobStatus.Running);
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([runningScan]));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenAQueuedScanIsInserted_ShouldPublishItsDomainEvents()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(Result.Created);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockUnitOfWork.LibraryScanRepository.Received(1).InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenInsertingTheQueuedScanFails_ShouldReturnError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
LibraryEntity library = _libraryEntityFixture.Create();
_mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryEntity>>([library]));
_mockUnitOfWork.LibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Result.From<IEnumerable<LibraryScanEntity>>([]));
Error error = Error.Failure("Database.Error", "Failed to insert the scan");
_mockUnitOfWork.LibraryScanRepository.InsertAsync(Arg.Any<LibraryScanEntity>(), Arg.Any<CancellationToken>())
.Returns(error);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(error, result.FirstError);
await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any<IDomainEvent>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,123 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
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
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="RepairThemesTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RepairThemesTaskExecutorTests
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly RepairThemesTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
private readonly PaginatedResultDtoFixture<ThemeEntity> _paginatedResultDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RepairThemesTaskExecutorTests"/> class.
/// </summary>
public RepairThemesTaskExecutorTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
ILogger<RepairThemesTaskExecutor> logger = Substitute.For<ILogger<RepairThemesTaskExecutor>>();
_sut = new RepairThemesTaskExecutor(_mockThemeService, logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldSynchronizeTheThemes()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenABundledThemeArchiveCannotBeRead_ShouldStillSucceed()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockThemeRepository.Received(1).GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationThrows_ShouldReturnFailure()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<PaginatedResultDto<ThemeEntity>>>(new InvalidOperationException("The database is unavailable.")));
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(nameof(RepairThemesTaskExecutor), result.FirstError.Description);
}
[Fact]
public async Task ExecutePayloadAsync_WhenTheSynchronizationIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.RepairThemes);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<PaginatedResultDto<ThemeEntity>>>(new OperationCanceledException()));
// Act
async Task Act()
{
await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Domain.SharedKernel.Common.Enums.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="TechnicalDataCleanupTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TechnicalDataCleanupTaskExecutorTests
{
private readonly IUnitOfWork _mockUnitOfWork;
private readonly ILibraryScanRepository _mockLibraryScanRepository;
private readonly TechnicalDataCleanupTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TechnicalDataCleanupTaskExecutorTests"/> class.
/// </summary>
public TechnicalDataCleanupTaskExecutorTests()
{
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockLibraryScanRepository = Substitute.For<ILibraryScanRepository>();
_mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository);
ILogger<TechnicalDataCleanupTaskExecutor> logger = Substitute.For<ILogger<TechnicalDataCleanupTaskExecutor>>();
_sut = new TechnicalDataCleanupTaskExecutor(logger, _mockUnitOfWork);
}
[Fact]
public async Task ExecutePayloadAsync_WhenCalled_ShouldFailTheInterruptedScans()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup);
_mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any<CancellationToken>()).Returns(Result.Updated);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
await _mockLibraryScanRepository.Received(1).FailInterruptedScansAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecutePayloadAsync_WhenFailingTheInterruptedScansFails_ShouldReturnTheError()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create(taskType: ScheduledTaskType.TechnicalDataCleanup);
Error expectedError = Error.Failure("Database.Error", "Failed to fail the interrupted scans");
_mockLibraryScanRepository.FailInterruptedScansAsync(Arg.Any<CancellationToken>()).Returns(expectedError);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(expectedError, result.FirstError);
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Lumina.Infrastructure.Core.Scheduling.Execution.TaskExecutors;
using Lumina.Domain.Fixtures.Core.BoundedContexts.SchedulingBoundedContext.ScheduledJobAggregate;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Execution.TaskExecutors;
/// <summary>
/// Contains unit tests for the <see cref="TemporaryFilesCleanupTaskExecutor"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class TemporaryFilesCleanupTaskExecutorTests
{
private readonly TemporaryFilesCleanupTaskExecutor _sut;
private readonly ScheduledJobFixture _scheduledJobFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="TemporaryFilesCleanupTaskExecutorTests"/> class.
/// </summary>
public TemporaryFilesCleanupTaskExecutorTests()
{
ILogger<TemporaryFilesCleanupTaskExecutor> logger = Substitute.For<ILogger<TemporaryFilesCleanupTaskExecutor>>();
_sut = new TemporaryFilesCleanupTaskExecutor(logger);
}
[Fact]
public async Task ExecutePayloadAsync_WhenTemporaryDirectoryExists_ShouldEmptyItAndReturnSuccess()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
Directory.CreateDirectory(Path.Combine(temporaryDirectory, "subdirectory"));
File.WriteAllText(Path.Combine(temporaryDirectory, "subdirectory", "file.txt"), "content");
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.True(Directory.Exists(temporaryDirectory));
Assert.Empty(Directory.GetFileSystemEntries(temporaryDirectory));
}
[Fact]
public async Task ExecutePayloadAsync_WhenTemporaryDirectoryDoesNotExist_ShouldRecreateItAndReturnSuccess()
{
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
if (Directory.Exists(temporaryDirectory))
Directory.Delete(temporaryDirectory, recursive: true);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Success, result.Value);
Assert.True(Directory.Exists(temporaryDirectory));
}
[Fact]
public async Task ExecutePayloadAsync_WhenDeletingTheDirectoryFails_ShouldReturnError()
{
// On non Windows platforms deleting a file that is locked open succeeds, so the failure path can only be forced on Windows.
if (!OperatingSystem.IsWindows())
return;
// Arrange
ScheduledJob scheduledJob = _scheduledJobFixture.Create();
string temporaryDirectory = Path.Combine(AppContext.BaseDirectory, "reading-cache");
Directory.CreateDirectory(temporaryDirectory);
string lockedFile = Path.Combine(temporaryDirectory, "locked.txt");
File.WriteAllText(lockedFile, "content");
// Lock the file with an exclusive handle so the recursive delete fails.
using FileStream lockStream = new(lockedFile, FileMode.Open, FileAccess.Read, FileShare.None);
// Act
Result<Success> result = await _sut.ExecutePayloadAsync(scheduledJob, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
}
}
@@ -0,0 +1,82 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.Fixtures.Core.Responses.Scheduling;
using Lumina.Contracts.Responses.Scheduling;
using Lumina.Infrastructure.Core.Scheduling.Notifications;
using Microsoft.AspNetCore.SignalR;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobNotifier"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobNotifierTests
{
private readonly IHubContext<ScheduledJobsHub, IScheduledJobsClient> _mockHubContext;
private readonly IHubClients<IScheduledJobsClient> _mockHubClients;
private readonly IScheduledJobsClient _mockClient;
private readonly ScheduledJobNotifier _sut;
private readonly ScheduledJobResponseFixture _scheduledJobResponseFixture = new();
private readonly ScheduledJobExecutionResponseFixture _scheduledJobExecutionResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobNotifierTests"/> class.
/// </summary>
public ScheduledJobNotifierTests()
{
_mockClient = Substitute.For<IScheduledJobsClient>();
_mockHubClients = Substitute.For<IHubClients<IScheduledJobsClient>>();
_mockHubClients.Group(ScheduledJobsHub.ADMINISTRATORS_GROUP).Returns(_mockClient);
_mockHubContext = Substitute.For<IHubContext<ScheduledJobsHub, IScheduledJobsClient>>();
_mockHubContext.Clients.Returns(_mockHubClients);
_sut = new ScheduledJobNotifier(_mockHubContext);
}
[Fact]
public async Task SendScheduledJobsAsync_WhenCalled_ShouldSendTheScheduledJobsToTheAdministratorGroup()
{
// Arrange
IReadOnlyList<ScheduledJobResponse> scheduledJobs = _scheduledJobResponseFixture.CreateMany(2);
// Act
await _sut.SendScheduledJobsAsync(scheduledJobs, CancellationToken.None);
// Assert
await _mockClient.Received(1).ReceiveScheduledJobsAsync(scheduledJobs);
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
}
[Fact]
public async Task SendScheduledJobExecutionStartedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup()
{
// Arrange
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
// Act
await _sut.SendScheduledJobExecutionStartedAsync(execution, CancellationToken.None);
// Assert
await _mockClient.Received(1).ScheduledJobExecutionStartedAsync(execution);
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
}
[Fact]
public async Task SendScheduledJobExecutionCompletedAsync_WhenCalled_ShouldSendTheExecutionToTheAdministratorGroup()
{
// Arrange
ScheduledJobExecutionResponse execution = _scheduledJobExecutionResponseFixture.Create();
// Act
await _sut.SendScheduledJobExecutionCompletedAsync(execution, CancellationToken.None);
// Assert
await _mockClient.Received(1).ScheduledJobExecutionCompletedAsync(execution);
_mockHubClients.Received(1).Group(ScheduledJobsHub.ADMINISTRATORS_GROUP);
}
}
@@ -0,0 +1,118 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Infrastructure.Core.Scheduling.Notifications;
using Microsoft.AspNetCore.SignalR;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Scheduling.Notifications;
/// <summary>
/// Contains unit tests for the <see cref="ScheduledJobsHub"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ScheduledJobsHubTests
{
private readonly IAuthorizationService _mockAuthorizationService;
private readonly ScheduledJobsHub _sut;
/// <summary>
/// Initializes a new instance of the <see cref="ScheduledJobsHubTests"/> class.
/// </summary>
public ScheduledJobsHubTests()
{
Microsoft.Extensions.DependencyInjection.IServiceScopeFactory mockScopeFactory = Substitute.For<Microsoft.Extensions.DependencyInjection.IServiceScopeFactory>();
Microsoft.Extensions.DependencyInjection.IServiceScope mockScope = Substitute.For<Microsoft.Extensions.DependencyInjection.IServiceScope>();
System.IServiceProvider mockServiceProvider = Substitute.For<System.IServiceProvider>();
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
mockScope.ServiceProvider.Returns(mockServiceProvider);
mockServiceProvider.GetService(typeof(IAuthorizationService)).Returns(_mockAuthorizationService);
mockScopeFactory.CreateScope().Returns(mockScope);
_sut = new ScheduledJobsHub(mockScopeFactory);
}
[Fact]
public async Task OnConnectedAsync_WhenUserClaimIsMissing_ShouldAbortTheConnection()
{
// Arrange
HubCallerContext context = CreateHubCallerContext(new ClaimsPrincipal(new ClaimsIdentity()));
_sut.Context = context;
// Act
await _sut.OnConnectedAsync();
// Assert
context.Received(1).Abort();
}
[Fact]
public async Task OnConnectedAsync_WhenUserIdClaimIsNotAGuid_ShouldAbortTheConnection()
{
// Arrange
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, "not-a-guid")]));
HubCallerContext context = CreateHubCallerContext(user);
_sut.Context = context;
// Act
await _sut.OnConnectedAsync();
// Assert
context.Received(1).Abort();
}
[Fact]
public async Task OnConnectedAsync_WhenUserIsNotAdministrator_ShouldAbortTheConnection()
{
// Arrange
Guid userId = Guid.NewGuid();
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
HubCallerContext context = CreateHubCallerContext(user);
_sut.Context = context;
_mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(false);
// Act
await _sut.OnConnectedAsync();
// Assert
context.Received(1).Abort();
}
[Fact]
public async Task OnConnectedAsync_WhenUserIsAdministrator_ShouldAddTheConnectionToTheAdministratorGroup()
{
// Arrange
Guid userId = Guid.NewGuid();
ClaimsPrincipal user = new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId.ToString())]));
HubCallerContext context = CreateHubCallerContext(user);
context.ConnectionId.Returns("connection-1");
_sut.Context = context;
IGroupManager mockGroupManager = Substitute.For<IGroupManager>();
_sut.Groups = mockGroupManager;
_mockAuthorizationService.IsInRoleAsync(userId, "Admin", System.Threading.CancellationToken.None).Returns(true);
// Act
await _sut.OnConnectedAsync();
// Assert
context.DidNotReceive().Abort();
await mockGroupManager.Received(1).AddToGroupAsync("connection-1", ScheduledJobsHub.ADMINISTRATORS_GROUP, System.Threading.CancellationToken.None);
}
/// <summary>
/// Creates a mocked hub caller context carrying the provided user.
/// </summary>
/// <param name="user">The user of the connection.</param>
/// <returns>The created context.</returns>
private static HubCallerContext CreateHubCallerContext(ClaimsPrincipal user)
{
HubCallerContext context = Substitute.For<HubCallerContext>();
context.User.Returns(user);
return context;
}
}
@@ -0,0 +1,161 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.Security;
using Lumina.Infrastructure.Fixtures.Core.Security;
using Microsoft.Extensions.Options;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="CryptographyService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CryptographyServiceTests
{
private readonly CryptographyService _sut;
private readonly IOptions<EncryptionSettingsDto> _encryptionSettings;
private readonly CryptographyServiceFixture _cryptographyServiceFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyServiceTests"/> class.
/// </summary>
public CryptographyServiceTests()
{
_encryptionSettings = _cryptographyServiceFixture.CreateEncryptionSettings();
_sut = new CryptographyService(_encryptionSettings);
}
[Fact]
public void Encrypt_WhenCalledWithValidData_ShouldReturnNonEmptyString()
{
// Arrange
string plaintext = _cryptographyServiceFixture.CreateTestData();
// Act
string result = _sut.Encrypt(plaintext);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.NotEqual(plaintext, result);
}
[Fact]
public void Encrypt_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentResults()
{
// Arrange
string plaintext = _cryptographyServiceFixture.CreateTestData();
// Act
string result1 = _sut.Encrypt(plaintext);
string result2 = _sut.Encrypt(plaintext);
// Assert
Assert.NotEqual(result1, result2);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Encrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
{
// Act
Action act = () => _sut.Encrypt(invalidInput!);
// Assert
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Encrypt(invalidInput!));
Assert.Equal("plaintext", exception.ParamName);
Assert.StartsWith("Value cannot be null or empty", exception.Message);
}
[Fact]
public void Decrypt_WhenCalledWithValidData_ShouldReturnOriginalText()
{
// Arrange
string originalText = _cryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(originalText);
// Act
string decrypted = _sut.Decrypt(encrypted);
// Assert
Assert.Equal(originalText, decrypted);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Decrypt_WhenInputIsNullOrEmpty_ShouldThrowArgumentException(string? invalidInput)
{
// Act
Action act = () => _sut.Decrypt(invalidInput!);
// Assert
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Decrypt(invalidInput!));
Assert.Equal("ciphertext", exception.ParamName);
Assert.StartsWith("Value cannot be null or empty", exception.Message);
}
[Theory]
[InlineData("invalid")]
[InlineData("not-base64-!@#")]
public void Decrypt_WhenInputIsNotBase64_ShouldThrowFormatException(string invalidInput)
{
// Act
Action act = () => _sut.Decrypt(invalidInput);
// Assert
Assert.Throws<FormatException>(() => _sut.Decrypt(invalidInput));
}
[Fact]
public void Decrypt_WhenInputIsTooShort_ShouldThrowArgumentException()
{
// Arrange
string shortCiphertext = Convert.ToBase64String(new byte[8]); // Less than required 16 bytes.
// Act
Action act = () => _sut.Decrypt(shortCiphertext);
// Assert
ArgumentException exception = Assert.Throws<ArgumentException>(() => _sut.Decrypt(shortCiphertext));
Assert.Equal("Invalid ciphertext", exception.Message);
}
[Fact]
public void Decrypt_WhenInputIsCorrupted_ShouldThrowCryptographicException()
{
// Arrange
string originalText = _cryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(originalText);
// Decode the Base64 string, modify one byte, then re-encode.
byte[] encryptedBytes = Convert.FromBase64String(encrypted);
encryptedBytes[^1] ^= 0xFF; // Flip all bits in the last byte.
string corrupted = Convert.ToBase64String(encryptedBytes);
// Act
Action act = () => _sut.Decrypt(corrupted);
// Assert
Assert.Throws<CryptographicException>(() => _sut.Decrypt(corrupted));
}
[Fact]
public void Dispose_WhenCalled_ShouldClearKey()
{
// Arrange
string plaintext = _cryptographyServiceFixture.CreateTestData();
string encrypted = _sut.Encrypt(plaintext);
// Act
_sut.Dispose();
// Assert
Assert.Throws<CryptographicException>(() => _sut.Decrypt(encrypted));
}
}
@@ -0,0 +1,157 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Security;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Security;
/// <summary>
/// Contains unit tests for the <see cref="PasswordHashService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class HashServiceTests
{
private readonly PasswordHashService _sut = new();
[Fact]
public void HashString_WhenCalled_ShouldReturnNonEmptyHash()
{
// Arrange
string password = "TestPassword123!";
// Act
string result = _sut.HashString(password);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(result);
Assert.NotEqual(password, result);
}
[Fact]
public void HashString_WhenCalledMultipleTimesWithSameInput_ShouldReturnDifferentHashes()
{
// Arrange
string password = "TestPassword123!";
// Act
string hash1 = _sut.HashString(password);
string hash2 = _sut.HashString(password);
// Assert
Assert.NotEqual(hash1, hash2);
}
[Theory]
[InlineData(" ")]
[InlineData("short")]
[InlineData("verylongpasswordwithlotsofcharactersbutnostringformatting")]
[InlineData("Password123!")]
[InlineData("@#$%^&*()")]
public void HashString_WhenCalledWithDifferentInputs_ShouldGenerateValidHashes(string input)
{
// Act
string hash = _sut.HashString(input);
// Assert
Assert.NotNull(hash);
Assert.NotEmpty(hash);
// Verify it's a valid Base64 string.
Assert.NotNull(Convert.FromBase64String(hash));
}
[Fact]
public void CheckStringAgainstHash_WhenPasswordMatches_ShouldReturnTrue()
{
// Arrange
string password = "TestPassword123!";
string hash = _sut.HashString(password);
// Act
bool result = _sut.CheckStringAgainstHash(password, hash);
// Assert
Assert.True(result);
}
[Fact]
public void CheckStringAgainstHash_WhenPasswordDoesNotMatch_ShouldReturnFalse()
{
// Arrange
string password = "TestPassword123!";
string wrongPassword = "WrongPassword123!";
string hash = _sut.HashString(password);
// Act
bool result = _sut.CheckStringAgainstHash(wrongPassword, hash);
// Assert
Assert.False(result);
}
[Theory]
[InlineData("")]
[InlineData("dGVzdA==")] // Valid base64 but wrong length.
[InlineData("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo=")] // Valid base64 but wrong length.
public void CheckStringAgainstHash_WhenHashIsInvalidLength_ShouldReturnFalse(string invalidHash)
{
// Arrange
string password = "TestPassword123!";
// Act
bool result = _sut.CheckStringAgainstHash(password, invalidHash);
// Assert
Assert.False(result);
}
[Fact]
public void CheckStringAgainstHash_WhenHashIsNotBase64_ShouldThrowFormatException()
{
// Arrange
string password = "TestPassword123!";
string invalidHash = "not-base64-string";
// Act
Action act = () => _sut.CheckStringAgainstHash(password, invalidHash);
// Assert
Assert.Throws<FormatException>(() => _sut.CheckStringAgainstHash(password, invalidHash));
}
[Theory]
[InlineData(null)]
public void HashString_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
{
// Act
Action act = () => _sut.HashString(nullPassword!);
// Assert
Assert.Throws<ArgumentNullException>(() => _sut.HashString(nullPassword!));
}
[Theory]
[InlineData(null)]
public void CheckStringAgainstHash_WhenPasswordIsNull_ShouldThrowArgumentNullException(string? nullPassword)
{
// Arrange
string hash = _sut.HashString("somepassword");
// Act
Action act = () => _sut.CheckStringAgainstHash(nullPassword!, hash);
// Assert
Assert.Throws<ArgumentNullException>(() => _sut.CheckStringAgainstHash(nullPassword!, hash));
}
[Fact]
public void CheckStringAgainstHash_WhenHashIsNull_ShouldThrowArgumentNullException()
{
// Act
Action act = () => _sut.CheckStringAgainstHash("password", null!);
// Assert
Assert.Throws<ArgumentNullException>(() => _sut.CheckStringAgainstHash("password", null!));
}
}
@@ -0,0 +1,81 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Themes;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeMimeTypes"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeMimeTypesTests
{
[Theory]
[InlineData("index.html", "text/html")]
[InlineData("index.htm", "text/html")]
[InlineData("style.css", "text/css")]
[InlineData("app.js", "application/javascript")]
[InlineData("manifest.json", "application/json")]
[InlineData("image.png", "image/png")]
[InlineData("photo.jpg", "image/jpeg")]
[InlineData("photo.jpeg", "image/jpeg")]
[InlineData("animation.gif", "image/gif")]
[InlineData("graphic.webp", "image/webp")]
[InlineData("icon.svg", "image/svg+xml")]
[InlineData("favicon.ico", "image/x-icon")]
[InlineData("font.woff", "font/woff")]
[InlineData("font.woff2", "font/woff2")]
[InlineData("font.ttf", "font/ttf")]
[InlineData("readme.txt", "text/plain")]
public void GetMimeType_WhenExtensionIsKnown_ShouldReturnMappedContentType(string filePath, string expectedContentType)
{
// Arrange
// filePath and expectedContentType are provided by the test data.
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal(expectedContentType, result);
}
[Fact]
public void GetMimeType_WhenExtensionIsUnknown_ShouldReturnApplicationOctetStream()
{
// Arrange
string filePath = "archive.unknown";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("application/octet-stream", result);
}
[Fact]
public void GetMimeType_WhenFileHasNoExtension_ShouldReturnApplicationOctetStream()
{
// Arrange
string filePath = "README";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("application/octet-stream", result);
}
[Fact]
public void GetMimeType_WhenExtensionIsMixedCase_ShouldResolveCaseInsensitively()
{
// Arrange
string filePath = "Photo.PNG";
// Act
string result = ThemeMimeTypes.GetMimeType(filePath);
// Assert
Assert.Equal("image/png", result);
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Lumina.Infrastructure.Core.Themes;
using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeServiceTests
{
private readonly string _storageRootPath;
private readonly ThemeEngineOptionsDto _options;
private readonly ThemeEngineOptionsDtoFixture _themeEngineOptionsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ThemeServiceTests"/> class.
/// </summary>
public ThemeServiceTests()
{
_storageRootPath = Path.Combine(Path.GetTempPath(), $"lumina-themes-{Guid.NewGuid():N}");
_options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_storageRootPath, "themes"),
bundledThemesPath: Path.Combine(_storageRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250);
}
[Fact]
public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_storageRootPath, "themes"),
bundledThemesPath: Path.Combine(_storageRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250);
options.MaxArchiveBytes = 12345;
ThemeService sut = CreateSut(options);
// Act
long result = sut.MaxArchiveBytes;
// Assert
Assert.Equal(12345, result);
}
[Fact]
public void DefaultThemeId_WhenConfigured_ShouldReturnConfiguredValue()
{
// Arrange
ThemeEngineOptionsDto options = _themeEngineOptionsDtoFixture.Create(
storagePath: Path.Combine(_storageRootPath, "themes"),
bundledThemesPath: Path.Combine(_storageRootPath, "bundled"),
defaultThemeId: "lumina-default",
maxArchiveBytes: 8 * 1024 * 1024,
maxExpandedBytes: 24 * 1024 * 1024,
maxSingleFileBytes: 6 * 1024 * 1024,
maxEntries: 250);
options.DefaultThemeId = "custom-default";
ThemeService sut = CreateSut(options);
// Act
string result = sut.DefaultThemeId;
// Assert
Assert.Equal("custom-default", result);
}
[Fact]
public async Task GetAssetAsync_WhenPathSegmentIsRenamedByPathService_ShouldReturnPackageInvalidError()
{
// Arrange
IPathService pathService = Substitute.For<IPathService>();
pathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo =>
{
string segment = callInfo.Arg<string>();
string sanitized = segment == "assets" ? "renamed-assets" : segment;
return PathSegment.Create(sanitized, isDirectory: true, isDrive: false);
});
ThemeService sut = new(Options.Create(_options), Substitute.For<ILogger<ThemeService>>(), pathService);
// Act
Result<ThemeAssetDto> result = await sut.GetAssetAsync("test-theme", "assets/logo.png", CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal("Theme.Package.Invalid", result.FirstError.Code);
}
/// <summary>
/// Creates a <see cref="ThemeService"/> instance using the provided options.
/// </summary>
/// <param name="options">The theme engine options to configure the service with.</param>
/// <returns>The created service.</returns>
private static ThemeService CreateSut(ThemeEngineOptionsDto options)
{
ILogger<ThemeService> logger = Substitute.For<ILogger<ThemeService>>();
IPathService pathService = Substitute.For<IPathService>();
pathService.SanitizeSegment(Arg.Any<string>())
.Returns(callInfo => PathSegment.Create(callInfo.Arg<string>(), isDirectory: true, isDrive: false));
return new ThemeService(Options.Create(options), logger, pathService);
}
}
@@ -0,0 +1,685 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Themes;
using Lumina.Application.Common.DataAccess.Repositories.Themes;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.Filtering;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Application.Common.Infrastructure.Themes;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes;
using Lumina.Application.Fixtures.Common.DTO.Pagination;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.Themes;
using Lumina.Infrastructure.Core.Themes;
using Microsoft.Extensions.Logging;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Themes;
/// <summary>
/// Contains unit tests for the <see cref="ThemeSynchronizer"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ThemeSynchronizerTests : IDisposable
{
private readonly IThemeService _mockThemeService;
private readonly IUnitOfWork _mockUnitOfWork;
private readonly IThemeRepository _mockThemeRepository;
private readonly ILogger _mockLogger;
private readonly ThemeEntityFixture _themeEntityFixture = new();
private readonly ThemeManifestDtoFixture _themeManifestDtoFixture = new();
private readonly PaginatedResultDtoFixture<ThemeEntity> _paginatedResultDtoFixture = new();
private readonly string _temporaryDirectoryPath;
/// <summary>
/// Initializes a new instance of the <see cref="ThemeSynchronizerTests"/> class.
/// </summary>
public ThemeSynchronizerTests()
{
_mockThemeService = Substitute.For<IThemeService>();
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
_mockThemeRepository = Substitute.For<IThemeRepository>();
_mockUnitOfWork.ThemeRepository.Returns(_mockThemeRepository);
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
_mockLogger = Substitute.For<ILogger>();
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
_mockThemeService.GetBundledThemeArchivePaths().Returns([]);
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(true);
_mockThemeService.DefaultThemeId.Returns("lumina-default");
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 0, count: 0, numberOfPages: 1)));
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Created);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>()).Returns(Result.Updated);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(Result.Deleted);
_temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), $"lumina-theme-sync-{Guid.NewGuid():N}");
Directory.CreateDirectory(_temporaryDirectoryPath);
}
[Fact]
public async Task SynchronizeAsync_WhenTheInstalledThemesCannotBeRead_ShouldLogAndReturn()
{
// Arrange
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().ReadManifestFromArchiveAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenLoggingIsDisabledAndTheInstalledThemesCannotBeRead_ShouldNotLogAWarning()
{
// Arrange
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(false);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.NotFound", "Failed to read the installed themes"));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.DidNotReceive().Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledArchiveManifestCannotBeRead_ShouldSkipThatArchive()
{
// Arrange
_mockThemeService.GetBundledThemeArchivePaths().Returns(["missing.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("missing.zip", Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Manifest", "Failed to read the theme manifest"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeIsAlreadyInstalledAtTheSameVersion_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.2.3");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.2.3", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeCarriesANewerVersion_ShouldReinstallItAndUpdateTheVersion()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.ThemeId == manifest.Id && theme.Version == "2.0.0"), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeWasSoftDeletedByTheUser_ShouldNotReinstallIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity deletedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [deletedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsMissingItsFiles_ShouldReinstallThemWithoutAddingANewRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
// The first pack check happens before the repair and reports the files as missing; the later checks report the files as present.
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheReinstallationFails_ShouldLogAndKeepTheExistingTheme()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
ThemeEntity damagedTheme = _themeEntityFixture.Create(themeId: manifest.Id, installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [damagedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(damagedTheme.ThemeId).Returns(false, true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Install", "Failed to install the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenANewBundledThemeIsInstalled_ShouldInsertTheThemeRow()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Is<ThemeEntity>(theme => theme.ThemeId == manifest.Id && theme.InstallSource == ThemeInstallSource.Bundled), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenPersistingANewBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.HasThemePack(manifest.Id).Returns(true);
_mockThemeRepository.InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.InsertFailed", "Failed to insert the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Is<object>(state => state.ToString()!.Contains("Failed to persist the detection of theme")),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheArchiveFileCannotBeRead_ShouldLogAndContinue()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string missingArchivePath = Path.Combine(_temporaryDirectoryPath, "missing.zip");
_mockThemeService.GetBundledThemeArchivePaths().Returns([missingArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(missingArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAccessToTheArchiveFileIsDenied_ShouldLogAndContinue()
{
// On non Windows platforms opening a directory behaves differently, so the test only asserts the denied access path on Windows.
if (!OperatingSystem.IsWindows())
return;
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create();
string deniedArchivePath = _temporaryDirectoryPath;
_mockThemeService.GetBundledThemeArchivePaths().Returns([deniedArchivePath]);
_mockThemeService.ReadManifestFromArchiveAsync(deniedArchivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAllThemesAreHealthyAndNoArchiveIsBundled_ShouldOnlyPersistTheChanges()
{
// Arrange
ThemeEntity healthyTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [healthyTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsBroken_ShouldRestoreItsFiles()
{
// Arrange
ThemeEntity brokenTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>()).Returns(Result.Success);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.Received(1).RestoreBundledThemeAsync(brokenTheme.ThemeId, Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenTheLastBundledThemeCannotBeRestored_ShouldKeepIt()
{
// Arrange
ThemeEntity lastBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [lastBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(lastBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(lastBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.False(lastBundledTheme.IsDeleted);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeCannotBeRestored_ShouldSoftDeleteIt()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.True(brokenBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenSoftDeletingABrokenBundledThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == brokenBundledTheme.Id), Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAUserThemeIsBroken_ShouldDeleteIt()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenDeletingABrokenUserThemeFails_ShouldLogAndContinue()
{
// Arrange
ThemeEntity brokenUserTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenUserTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenUserTheme.ThemeId).Returns(false);
_mockThemeRepository.DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.DeleteFailed", "Failed to delete the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeRepository.Received(1).DeleteByIdAsync(brokenUserTheme.Id, Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingOneBrokenThemeThrows_ShouldContinueWithTheRemainingBrokenThemes()
{
// Arrange
ThemeEntity throwingBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity healthyBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [throwingBundledTheme, healthyBundledTheme], currentPage: 1, perPage: 2, count: 2, numberOfPages: 1)));
_mockThemeService.HasThemePack(Arg.Any<string>()).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(throwingBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new InvalidOperationException("Unexpected failure")));
_mockThemeService.RestoreBundledThemeAsync(healthyBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Error.Failure("Theme.Restore", "Failed to restore the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
// The second broken bundled theme is still soft deleted even though the first one threw.
Assert.True(healthyBundledTheme.IsDeleted);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == healthyBundledTheme.Id), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRepairingABrokenThemeIsCancelled_ShouldRethrowTheCancellation()
{
// Arrange
ThemeEntity brokenBundledTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [brokenBundledTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.HasThemePack(brokenBundledTheme.ThemeId).Returns(false);
_mockThemeService.RestoreBundledThemeAsync(brokenBundledTheme.ThemeId, Arg.Any<CancellationToken>())
.Returns(Task.FromException<Result<Success>>(new OperationCanceledException()));
// Act
async Task Act()
{
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(Act);
}
[Fact]
public async Task SynchronizeAsync_WhenTheBundledThemeVersionDiffers_ShouldRefreshTheVersion()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(
themeId: manifest.Id,
version: "1.0.0",
installSource: ThemeInstallSource.Bundled,
isDeleted: false,
includeIsCurrent: true,
isCurrent: true,
includeUpdatedOnUtc: true,
updatedOnUtc: DateTime.UtcNow.AddDays(-1),
includeUpdatedBy: true,
updatedBy: Guid.NewGuid());
DateTime? initialUpdatedOnUtc = installedTheme.UpdatedOnUtc;
Guid? initialUpdatedBy = installedTheme.UpdatedBy;
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
Assert.Equal("3.0.0", installedTheme.Version);
Assert.Equal(initialUpdatedOnUtc, installedTheme.UpdatedOnUtc);
Assert.Equal(initialUpdatedBy, installedTheme.UpdatedBy);
await _mockThemeRepository.Received(1).UpdateAsync(
Arg.Is<ThemeEntity>(theme => theme.Id == installedTheme.Id && theme.Version == "3.0.0"),
Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenRefreshingTheInstalledThemeVersionFails_ShouldLogAndContinueWithoutThrowing()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "3.0.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeService.InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.UpdateFailed", "Failed to update the theme"));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenAThemeWithTheSameIdWasInstalledFromAnotherSource_ShouldSkipTheBundledArchive()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "2.0.0");
ThemeEntity uploadedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.0.0", installSource: ThemeInstallSource.Uploaded, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [uploadedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
_mockThemeService.GetBundledThemeArchivePaths().Returns(["bundled.zip"]);
_mockThemeService.HasThemePack(uploadedTheme.ThemeId).Returns(true);
_mockThemeService.ReadManifestFromArchiveAsync("bundled.zip", Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task SynchronizeAsync_WhenABundledThemeIsAlreadyInstalledAndUpToDate_ShouldSkipIt()
{
// Arrange
ThemeManifestDto manifest = _themeManifestDtoFixture.Create(version: "1.5.0");
ThemeEntity installedTheme = _themeEntityFixture.Create(themeId: manifest.Id, version: "1.5.0", installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
_mockThemeRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>()).Returns(Result.From(_paginatedResultDtoFixture.Create(data: [installedTheme], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
string archivePath = CreateArchiveFile();
_mockThemeService.GetBundledThemeArchivePaths().Returns([archivePath]);
_mockThemeService.HasThemePack(installedTheme.ThemeId).Returns(true);
_mockThemeService.ReadManifestFromArchiveAsync(archivePath, Arg.Any<CancellationToken>()).Returns(Result.From(manifest));
// Act
await ThemeSynchronizer.SynchronizeAsync(_mockThemeService, _mockUnitOfWork, _mockLogger, CancellationToken.None);
// Assert
await _mockThemeService.DidNotReceive().InstallAsync(Arg.Any<Stream>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().InsertAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenANonDeletedThemeIsCurrent_ShouldNotSelectAnotherTheme()
{
// Arrange
ThemeEntity currentTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: false, includeIsCurrent: true, isCurrent: true);
ThemeEntity otherTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([currentTheme, otherTheme]);
// Assert
Assert.True(currentTheme.IsCurrent);
Assert.NotEqual(true, otherTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeCanBeSelected_ShouldNotSelectAnyTheme()
{
// Arrange
ThemeEntity deletedTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Bundled, isDeleted: true);
// Act
await InvokeEnsureCurrentThemeExistsAsync([deletedTheme]);
// Assert
Assert.NotEqual(true, deletedTheme.IsCurrent);
await _mockThemeRepository.DidNotReceive().UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenNoThemeIsCurrent_ShouldActivateTheDefaultTheme()
{
// Arrange
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
ThemeEntity userTheme = _themeEntityFixture.Create(installSource: ThemeInstallSource.Uploaded, isDeleted: false);
_mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true);
_mockThemeService.HasThemePack(userTheme.ThemeId).Returns(false);
// Act
await InvokeEnsureCurrentThemeExistsAsync([userTheme, defaultTheme]);
// Assert
Assert.True(defaultTheme.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
}
[Fact]
public async Task EnsureCurrentThemeExistsAsync_WhenActivatingTheDefaultThemeFails_ShouldLogAndNotThrow()
{
// Arrange
ThemeEntity defaultTheme = _themeEntityFixture.Create(themeId: "lumina-default", installSource: ThemeInstallSource.Bundled, isDeleted: false);
_mockThemeService.HasThemePack(defaultTheme.ThemeId).Returns(true);
_mockThemeRepository.UpdateAsync(Arg.Any<ThemeEntity>(), Arg.Any<CancellationToken>())
.Returns(Error.Failure("Themes.UpdateFailed", "Failed to activate the theme"));
// Act
await InvokeEnsureCurrentThemeExistsAsync([defaultTheme]);
// Assert
Assert.True(defaultTheme.IsCurrent);
await _mockThemeRepository.Received(1).UpdateAsync(Arg.Is<ThemeEntity>(theme => theme.Id == defaultTheme.Id), Arg.Any<CancellationToken>());
// A failed activation must not be silent, so it is logged instead of being discarded.
_mockLogger.Received(1).Log(
LogLevel.Warning,
Arg.Any<EventId>(),
Arg.Any<object>(),
Arg.Any<Exception?>(),
Arg.Any<Func<object, Exception?, string>>());
}
/// <summary>
/// Creates a real archive file on disk so that <see cref="ThemeSynchronizer"/> can open it.
/// </summary>
/// <returns>The path of the created archive file.</returns>
private string CreateArchiveFile()
{
string archivePath = Path.Combine(_temporaryDirectoryPath, $"theme-{Guid.NewGuid():N}.zip");
File.WriteAllText(archivePath, "theme-pack");
return archivePath;
}
/// <summary>
/// Invokes the private <c>EnsureCurrentThemeExistsAsync</c> method of the synchronizer.
/// </summary>
/// <param name="themes">The installed themes passed to the method.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
private async Task InvokeEnsureCurrentThemeExistsAsync(IReadOnlyList<ThemeEntity> themes)
{
MethodInfo method = typeof(ThemeSynchronizer).GetMethod("EnsureCurrentThemeExistsAsync", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("The method 'EnsureCurrentThemeExistsAsync' was not found on the theme synchronizer.");
Task task = (Task)method.Invoke(null, [_mockThemeService, _mockUnitOfWork, themes, _mockLogger, CancellationToken.None])!;
await task.ConfigureAwait(false);
}
/// <summary>
/// Removes the temporary files created by the tests.
/// </summary>
public void Dispose()
{
if (Directory.Exists(_temporaryDirectoryPath))
Directory.Delete(_temporaryDirectoryPath, recursive: true);
}
}
@@ -0,0 +1,40 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Infrastructure.Core.Time;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Infrastructure.UnitTests.Core.Time;
/// <summary>
/// Contains unit tests for the <see cref="DateTimeProvider"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DateTimeProviderTests
{
private readonly DateTimeProvider _sut = new();
[Fact]
public void UtcNow_WhenCalled_ShouldReturnCurrentUtcTime()
{
// Arrange
DateTime before = DateTime.UtcNow;
// Act
DateTime result = _sut.UtcNow;
// Assert
DateTime after = DateTime.UtcNow;
Assert.True(result >= before && result <= after);
}
[Fact]
public void UtcNow_WhenCalled_ShouldReturnUtcKind()
{
// Act
DateTime result = _sut.UtcNow;
// Assert
Assert.Equal(DateTimeKind.Utc, result.Kind);
}
}
@@ -0,0 +1,50 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Xunit.CollectionBehaviorAttribute">
<_Parameter1>DisableTestParallelization = true</_Parameter1>
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Http.Features" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="NSubstitute" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\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>
</Project>