Hardens test assertions and adds missing test coverage.

This commit is contained in:
BinaryAlley committed 2026-08-18 08:28:16 -07:00
1 parent 6b86fd5805
commit 1189bbaf36
489 files changed
+39982 -512

No files matched your search

@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DomainEvents;
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.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.Core.Plugins;
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.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#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(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));
}
[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>));
}
/// <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();
}
}
@@ -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,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,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,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);
}
}