Adds the test suites for the library path templates and centralizes their resolution in the domain service

This commit is contained in:
BinaryAlley committed 2026-10-05 20:15:00 +03:00
1 parent ca4f308b0a
commit 7ed6f05632
52 files changed
+4724 -40

No files matched your search

@@ -3,12 +3,14 @@ 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.DomainEvents;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
@@ -17,12 +19,14 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -49,6 +53,9 @@ public class AddLibraryCommandHandlerTests
private readonly AddLibraryCommandHandler _sut;
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -79,8 +86,7 @@ public class AddLibraryCommandHandlerTests
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<AddLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any<LibraryType>()).Returns(LibraryPathTemplate.Empty());
_mockLibraryPathTemplateService.Validate(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>()).Returns(Result.Success);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
_sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator);
}
@@ -296,4 +302,118 @@ public class AddLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(defaultTemplate));
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts => parts.Count == 0));
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts()
{
// Arrange
LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: false);
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(resolvedTemplate));
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts =>
parts.Count == 1 &&
parts[0].Kind == LibraryPathPartKind.Artist &&
parts[0].Representation == "{0}" &&
!parts[0].IsOptional));
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
!library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
_mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>());
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(validationError);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -18,6 +21,7 @@ public class AddLibraryCommandValidatorTests
{
private readonly AddLibraryCommandValidator _validator = new();
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
@@ -201,6 +205,92 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
[Fact]
public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists");
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
@@ -3,6 +3,7 @@ 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.DomainEvents;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
@@ -10,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
@@ -18,6 +20,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
@@ -25,6 +28,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -51,6 +55,9 @@ public class UpdateLibraryCommandHandlerTests
private readonly UpdateLibraryCommandHandler _sut;
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -82,8 +89,7 @@ public class UpdateLibraryCommandHandlerTests
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<UpdateLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any<LibraryType>()).Returns(LibraryPathTemplate.Empty());
_mockLibraryPathTemplateService.Validate(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>()).Returns(Result.Success);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
_sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator);
}
@@ -422,4 +428,124 @@ public class UpdateLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(defaultTemplate));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts => parts.Count == 0));
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts()
{
// Arrange
LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: false);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(resolvedTemplate));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts =>
parts.Count == 1 &&
parts[0].Kind == LibraryPathPartKind.Artist &&
parts[0].Representation == "{0}" &&
!parts[0].IsOptional));
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
!library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
_mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(validationError);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -19,6 +22,7 @@ public class UpdateLibraryCommandValidatorTests
{
private readonly UpdateLibraryCommandValidator _validator = new();
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
@@ -256,6 +260,92 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
[Fact]
public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists");
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
@@ -0,0 +1,169 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
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.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsQueryHandlerTests
{
private readonly ILibraryPathPartCatalog _mockBookCatalog;
private readonly ILibraryPathPartCatalog _mockMusicCatalog;
private readonly GetLibraryPathTemplatePartsQueryHandler _sut;
private readonly GetLibraryPathTemplatePartsQueryFixture _getLibraryPathTemplatePartsQueryFixture = new();
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsQueryHandlerTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsQueryHandlerTests()
{
_mockBookCatalog = Substitute.For<ILibraryPathPartCatalog>();
_mockBookCatalog.SupportedLibraryType.Returns(LibraryType.Book);
_mockBookCatalog.GetPartDefinitions().Returns([]);
_mockBookCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty());
_mockMusicCatalog = Substitute.For<ILibraryPathPartCatalog>();
_mockMusicCatalog.SupportedLibraryType.Returns(LibraryType.Music);
_mockMusicCatalog.GetPartDefinitions().Returns([]);
_mockMusicCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty());
_sut = new GetLibraryPathTemplatePartsQueryHandler([_mockBookCatalog, _mockMusicCatalog]);
}
[Theory]
[InlineData("")] // an absent library type
[InlineData(" ")] // a whitespace library type
[InlineData("NotARealLibraryType")] // an unknown library type
public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType)
{
// Arrange
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: libraryType);
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.UnknownLibraryType, result.FirstError);
_ = _mockBookCatalog.DidNotReceive().SupportedLibraryType;
_ = _mockMusicCatalog.DidNotReceive().SupportedLibraryType;
}
[Fact]
public async Task HandleAsync_WhenNoCatalogSupportsLibraryType_ShouldReturnEmptyPartsAndDefaultTemplateParts()
{
// Arrange
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Photo));
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Parts);
Assert.Empty(result.Value.DefaultTemplateParts);
_ = _mockBookCatalog.Received(1).SupportedLibraryType;
_ = _mockMusicCatalog.Received(1).SupportedLibraryType;
_mockBookCatalog.DidNotReceive().GetPartDefinitions();
_mockBookCatalog.DidNotReceive().GetDefaultTemplate();
_mockMusicCatalog.DidNotReceive().GetPartDefinitions();
_mockMusicCatalog.DidNotReceive().GetDefaultTemplate();
}
[Fact]
public async Task HandleAsync_WhenCatalogSupportsLibraryType_ShouldMapPartDefinitionsAndDefaultTemplatePartsInOrder()
{
// Arrange
List<LibraryPathPartDefinition> partDefinitions =
[
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false),
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: true),
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "{0}",
isOptionalByDefault: false)
];
_mockMusicCatalog.GetPartDefinitions().Returns(partDefinitions);
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathPart separatorPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Separator,
representation: string.Empty,
isOptional: false);
LibraryPathPart trackNamePart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.TrackName,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [artistPart, separatorPart, trackNamePart]);
_mockMusicCatalog.GetDefaultTemplate().Returns(defaultTemplate);
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Music));
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Parts.Count);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.Parts[0].Kind);
Assert.Equal(LibraryPathValueType.Text.ToString(), result.Value.Parts[0].ValueType);
Assert.Equal("{0}", result.Value.Parts[0].DefaultRepresentation);
Assert.False(result.Value.Parts[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackNumber.ToString(), result.Value.Parts[1].Kind);
Assert.Equal(LibraryPathValueType.Integer.ToString(), result.Value.Parts[1].ValueType);
Assert.Equal("{0:00}", result.Value.Parts[1].DefaultRepresentation);
Assert.True(result.Value.Parts[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseYear.ToString(), result.Value.Parts[2].Kind);
Assert.Equal(LibraryPathValueType.Year.ToString(), result.Value.Parts[2].ValueType);
Assert.Equal("{0}", result.Value.Parts[2].DefaultRepresentation);
Assert.False(result.Value.Parts[2].IsOptionalByDefault);
Assert.Equal(3, result.Value.DefaultTemplateParts.Count);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.DefaultTemplateParts[0].Kind);
Assert.Equal("{0}", result.Value.DefaultTemplateParts[0].Representation);
Assert.False(result.Value.DefaultTemplateParts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.Value.DefaultTemplateParts[1].Kind);
Assert.Equal(string.Empty, result.Value.DefaultTemplateParts[1].Representation);
Assert.False(result.Value.DefaultTemplateParts[1].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackName.ToString(), result.Value.DefaultTemplateParts[2].Kind);
Assert.Equal("{0}", result.Value.DefaultTemplateParts[2].Representation);
Assert.True(result.Value.DefaultTemplateParts[2].IsOptional);
_mockMusicCatalog.Received(1).GetPartDefinitions();
_mockMusicCatalog.Received(1).GetDefaultTemplate();
_mockBookCatalog.DidNotReceive().GetPartDefinitions();
_mockBookCatalog.DidNotReceive().GetDefaultTemplate();
}
}