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

@@ -16,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
@@ -144,4 +145,45 @@ public class AddMediaLibraryRequestMappingTests
Assert.NotNull(result);
Assert.Null(result.CoverImage);
}
[Fact]
public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray()
{
// Arrange
LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.PathTemplateParts);
Assert.Equal(2, result.PathTemplateParts.Length);
Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind);
Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation);
Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional);
Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind);
Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation);
Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional);
}
[Fact]
public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.PathTemplateParts);
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsRequestMappingTests
{
private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapLibraryType()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Book");
// Act
GetLibraryPathTemplatePartsQuery result = request.ToQuery();
// Assert
Assert.Equal("Book", result.LibraryType);
}
[Theory]
[InlineData("Book")] // a written content library type
[InlineData("Movie")] // a video library type
[InlineData("Music")] // an audio library type
public void ToQuery_WhenMappingDifferentLibraryTypes_ShouldMapLibraryType(string libraryType)
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: libraryType);
// Act
GetLibraryPathTemplatePartsQuery result = request.ToQuery();
// Assert
Assert.Equal(libraryType, result.LibraryType);
}
}
@@ -3,10 +3,14 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -18,6 +22,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class LibraryEntityMappingTests
{
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly()
@@ -123,4 +128,126 @@ public class LibraryEntityMappingTests
Assert.NotNull(result);
Assert.Null(result.CoverImage);
}
[Fact]
public void ToResponse_WhenLibraryHasPathTemplateParts_ShouldOrderByPositionAndMapProperties()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(
position: 2,
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Literal,
representation: "Various Artists");
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(
position: 1,
kind: LibraryPathPartKind.Separator,
representation: string.Empty);
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [firstPart, secondPart, thirdPart]);
// Act
LibraryResponse result = entity.ToResponse();
// Assert
Assert.Equal(3, result.PathTemplateParts.Count);
Assert.Equal(LibraryPathPartKind.Literal.ToString(), result.PathTemplateParts[0].Kind);
Assert.Equal("Various Artists", result.PathTemplateParts[0].Representation);
Assert.False(result.PathTemplateParts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.PathTemplateParts[1].Kind);
Assert.Equal(string.Empty, result.PathTemplateParts[1].Representation);
Assert.False(result.PathTemplateParts[1].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.PathTemplateParts[2].Kind);
Assert.Equal("{0}", result.PathTemplateParts[2].Representation);
Assert.True(result.PathTemplateParts[2].IsOptional);
}
[Fact]
public void ToDomainEntity_WhenLibraryHasPathTemplateParts_ShouldBuildTemplateFromOrderedParts()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(
position: 1,
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Literal,
representation: "Various Artists");
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
coverImage: "D:/cover.jpg",
pathTemplateParts: [firstPart, secondPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(entity.Id, result.Value.Id.Value);
Assert.Equal(entity.UserId, result.Value.UserId.Value);
Assert.Equal(entity.Title, result.Value.Title);
Assert.Equal(entity.LibraryType, result.Value.LibraryType);
Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value);
Assert.Equal(2, result.Value.PathTemplate.Parts.Count);
Assert.Equal(LibraryPathPartKind.Literal, result.Value.PathTemplate.Parts[0].Kind);
Assert.Equal("Various Artists", result.Value.PathTemplate.Parts[0].Representation);
Assert.False(result.Value.PathTemplate.Parts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist, result.Value.PathTemplate.Parts[1].Kind);
Assert.Equal("{0}", result.Value.PathTemplate.Parts[1].Representation);
Assert.True(result.Value.PathTemplate.Parts[1].IsOptional);
}
[Fact]
public void ToDomainEntity_WhenStoredTypedPartHasEmptyRepresentation_ShouldReturnPathTemplateLiteralCannotBeEmpty()
{
// Arrange
LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Artist,
representation: string.Empty);
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [invalidPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void ToDomainEntity_WhenStoredTypedPartHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.TrackNumber,
representation: "Track");
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [invalidPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
}
@@ -4,7 +4,9 @@ using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
@@ -21,6 +23,8 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class LibraryMappingTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
[Fact]
public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly()
@@ -185,4 +189,57 @@ public class LibraryMappingTests
Assert.NotNull(library.ScanIds);
Assert.NotNull(result.LibraryScans);
}
[Fact]
public void ToRepositoryEntity_WhenLibraryHasPathTemplateParts_ShouldMapPartsWithSequentialPositions()
{
// Arrange
LibraryPathPart literalPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Literal,
representation: "Various Artists",
isOptional: false);
LibraryPathPart typedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(parts: [literalPart, typedPart]);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplate: pathTemplate);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
List<LibraryPathTemplatePartEntity> parts = [.. result.PathTemplateParts.OrderBy(part => part.Position)];
Assert.Equal(2, parts.Count);
Assert.Equal(0, parts[0].Position);
Assert.Equal(LibraryPathPartKind.Literal, parts[0].Kind);
Assert.Equal("Various Artists", parts[0].Representation);
Assert.False(parts[0].IsOptional);
Assert.Equal(1, parts[1].Position);
Assert.Equal(LibraryPathPartKind.Artist, parts[1].Kind);
Assert.Equal("{0}", parts[1].Representation);
Assert.True(parts[1].IsOptional);
}
[Fact]
public void ToRepositoryEntity_WhenLibraryHasNoPathTemplateParts_ShouldMapEmptyCollection()
{
// Arrange
LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(includeParts: false);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplate: pathTemplate);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
Assert.Empty(result.PathTemplateParts);
}
}
@@ -0,0 +1,204 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplatePartDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartDtoMappingTests
{
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void ToDomainParts_WhenPartsIsNull_ShouldReturnEmptyList()
{
// Act
Result<IReadOnlyList<LibraryPathPart>> result = LibraryPathTemplatePartDtoMapping.ToDomainParts(null);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public void ToDomainParts_WhenPartsIsEmpty_ShouldReturnEmptyList()
{
// Arrange
List<LibraryPathTemplatePartDto> parts = [];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public void ToDomainParts_WhenPartsAreValid_ShouldMapKindRepresentationAndIsOptional()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartDto[] parts = [literalPart, typedPart];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(LibraryPathPartKind.Literal, result.Value[0].Kind);
Assert.Equal("Various Artists", result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist, result.Value[1].Kind);
Assert.Equal("{0}", result.Value[1].Representation);
Assert.True(result.Value[1].IsOptional);
}
[Fact]
public void ToDomainParts_WhenPartIsSeparator_ShouldMapWithEmptyRepresentation()
{
// Arrange
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: @"\",
isOptional: false);
LibraryPathTemplatePartDto[] parts = [separatorPart];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(LibraryPathPartKind.Separator, result.Value[0].Kind);
Assert.Equal(string.Empty, result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
}
[Fact]
public void ToDomainParts_WhenKindIsUnknown_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: "NotARealLibraryPathPartKind");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenKindIsNull_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = null };
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenKindUsesDifferentCasing_ShouldMapKind()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: "artist",
representation: "{0}",
isOptional: false);
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(LibraryPathPartKind.Artist, result.Value[0].Kind);
Assert.Equal("{0}", result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationIsEmpty_ShouldReturnPathTemplateLiteralCannotBeEmpty()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: string.Empty);
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "Artist Name");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationHasDuplicatePlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0} - {0}");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -15,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class UpdateLibraryRequestMappingTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
@@ -46,4 +48,45 @@ public class UpdateLibraryRequestMappingTests
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan);
}
[Fact]
public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray()
{
// Arrange
LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.PathTemplateParts);
Assert.Equal(2, result.PathTemplateParts.Length);
Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind);
Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation);
Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional);
Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind);
Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation);
Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional);
}
[Fact]
public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.PathTemplateParts);
}
}
@@ -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();
}
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
@@ -28,6 +29,11 @@ public class LibraryConfigurationTests
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
@@ -64,6 +70,22 @@ public class LibraryConfigurationTests
Assert.Equal(true, downloadMetadataProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigurePathTemplateFingerprint()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty fingerprintProperty = entityType.GetProperty(nameof(LibraryEntity.PathTemplateFingerprint));
// Assert
Assert.True(fingerprintProperty.IsNullable);
Assert.Equal(typeof(string), fingerprintProperty.ClrType);
Assert.Equal(64, fingerprintProperty.GetMaxLength());
Assert.Equal(11, fingerprintProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations()
{
@@ -71,15 +93,78 @@ public class LibraryConfigurationTests
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
IEntityType contentLocationType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryContentLocationEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
// Assert
IEntityType contentLocationType = Assert.Single(ownedTypes);
Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType);
Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName());
Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplateParts()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IEntityType partEntityType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
IForeignKey ownershipForeignKey = partEntityType.FindOwnership()!;
// Assert
Assert.Equal("LibraryPathTemplateParts", partEntityType.GetTableName());
Assert.Equal(["Id"], partEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
Assert.Equal(typeof(LibraryEntity), ownershipForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(["LibraryId"], ownershipForeignKey.Properties.Select(property => property.Name));
Assert.True(ownershipForeignKey.IsRequired);
IIndex uniqueIndex = Assert.Single(
partEntityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(["LibraryId", nameof(LibraryPathTemplatePartEntity.Position)]));
Assert.True(uniqueIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplatePartColumns()
{
// Arrange
IEntityType partEntityType = DesignTimeModel.GetEntityTypes()
.Single(entityType => entityType.IsOwned()
&& entityType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& entityType.GetTableName() == "LibraryPathTemplateParts");
// Act
IProperty positionProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Position));
IProperty kindProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Kind));
IProperty representationProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Representation));
IProperty isOptionalProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.IsOptional));
// Assert
Assert.Equal("Position", positionProperty.GetColumnName());
Assert.False(positionProperty.IsNullable);
Assert.Equal(typeof(LibraryPathPartKind), kindProperty.ClrType);
Assert.Equal(typeof(string), kindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", kindProperty.GetColumnType());
Assert.Equal(32, kindProperty.GetMaxLength());
Assert.False(kindProperty.IsNullable);
Assert.Equal(512, representationProperty.GetMaxLength());
Assert.False(representationProperty.IsNullable);
Assert.Equal(typeof(bool), isOptionalProperty.ClrType);
Assert.False(isOptionalProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationships()
{
@@ -111,4 +196,23 @@ public class LibraryConfigurationTests
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditColumnOrders()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedBy));
// Assert
Assert.Equal(12, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(13, createdByProperty.GetColumnOrder());
Assert.Equal(14, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(15, updatedByProperty.GetColumnOrder());
}
}
@@ -8,6 +8,7 @@ using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -29,6 +30,7 @@ public class LibraryRepositoryTests
private readonly LuminaDbContext _mockContext;
private readonly LibraryRepository _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryRepositoryTests"/> class.
@@ -230,4 +232,307 @@ public class LibraryRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
}
[Fact]
public async Task InsertAsync_WhenLibraryHasPathTemplateParts_ShouldAddLibraryAndItsPartsToContext()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Separator, representation: "/", isOptional: false);
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity library = _libraryEntityFixture.Create(
contentLocations: [],
pathTemplateParts: [firstPart, secondPart, thirdPart],
pathTemplateFingerprint: "path-template-fingerprint");
// Act
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<LibraryEntity>? addedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id);
Assert.NotNull(addedLibrary);
Assert.Equal("path-template-fingerprint", addedLibrary!.Entity.PathTemplateFingerprint);
List<EntityEntry<LibraryPathTemplatePartEntity>> partEntries = [.. _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.Where(entityEntry => entityEntry.State == EntityState.Added)];
Assert.Equal(3, partEntries.Count);
Assert.Equal([0, 1, 2], partEntries.Select(entityEntry => entityEntry.Entity.Position).OrderBy(position => position));
LibraryPathTemplatePartEntity storedFirstPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 0).Entity;
Assert.Equal(LibraryPathPartKind.Artist, storedFirstPart.Kind);
Assert.Equal("{0}", storedFirstPart.Representation);
Assert.False(storedFirstPart.IsOptional);
LibraryPathTemplatePartEntity storedSecondPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 1).Entity;
Assert.Equal(LibraryPathPartKind.Separator, storedSecondPart.Kind);
Assert.Equal("/", storedSecondPart.Representation);
Assert.False(storedSecondPart.IsOptional);
LibraryPathTemplatePartEntity storedThirdPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 2).Entity;
Assert.Equal(LibraryPathPartKind.Series, storedThirdPart.Kind);
Assert.Equal("{0}", storedThirdPart.Representation);
Assert.True(storedThirdPart.IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartRepresentationChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{1}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
EntityEntry<LibraryPathTemplatePartEntity>? keptEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, keptPart));
Assert.NotNull(keptEntry);
Assert.Equal(EntityState.Unchanged, keptEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
Assert.False(retrievedResult.IsFailure);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal("{0}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0).Representation);
Assert.Equal("{1}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Representation);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartKindChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(LibraryPathPartKind.Series, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Kind);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartIsOptionalChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.True(retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartPositionIsRemoved_ShouldRemoveThatPart()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity removedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, removedPart, thirdPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [firstPart, thirdPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? removedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, removedPart));
Assert.NotNull(removedEntry);
Assert.Equal(EntityState.Deleted, removedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal([0, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartPositionIsAdded_ShouldAddThatPart()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity addedPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [firstPart, secondPart, addedPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? addedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, addedPart));
Assert.NotNull(addedEntry);
Assert.Equal(EntityState.Added, addedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(3, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal([0, 1, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
LibraryPathTemplatePartEntity storedAddedPart = retrievedLibrary.PathTemplateParts.Single(part => part.Position == 2);
Assert.Equal(LibraryPathPartKind.Series, storedAddedPart.Kind);
Assert.Equal("{0}", storedAddedPart.Representation);
Assert.True(storedAddedPart.IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartsAreUnchanged_ShouldKeepExistingParts()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity equivalentFirstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity equivalentSecondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [equivalentFirstPart, equivalentSecondPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.DoesNotContain(
_mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>(),
entityEntry => entityEntry.State == EntityState.Added || entityEntry.State == EntityState.Deleted);
EntityEntry<LibraryPathTemplatePartEntity>? firstEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, firstPart));
Assert.NotNull(firstEntry);
Assert.Equal(EntityState.Unchanged, firstEntry!.State);
EntityEntry<LibraryPathTemplatePartEntity>? secondEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, secondPart));
Assert.NotNull(secondEntry);
Assert.Equal(EntityState.Unchanged, secondEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Same(firstPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0));
Assert.Same(secondPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1));
}
[Fact]
public async Task UpdateAsync_WhenPathTemplateFingerprintChanges_ShouldUpdateIt()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [], pathTemplateFingerprint: "old-fingerprint");
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [],
pathTemplateFingerprint: "new-fingerprint");
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id);
Assert.NotNull(retrievedLibrary);
Assert.Equal("new-fingerprint", retrievedLibrary!.PathTemplateFingerprint);
}
}
@@ -42,7 +42,7 @@ public class ErrorsTests
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(14, typeof(DomainErrors.Library).GetProperties().Length);
Assert.Equal(18, typeof(DomainErrors.Library).GetProperties().Length);
AssertError(DomainErrors.Library.CannotScanLockedLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.CannotScanDisabledLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.LibraryIdCannotBeEmpty, ErrorType.Validation);
@@ -52,11 +52,15 @@ public class ErrorsTests
AssertError(DomainErrors.Library.LibraryNotFound, ErrorType.NotFound);
AssertError(DomainErrors.Library.LibraryTypeCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.CoverFileMustBeAnImage, ErrorType.Validation);
AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Unexpected);
AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Forbidden);
AssertError(DomainErrors.Library.PathsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.PathsListCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleMustBeMaximum255CharactersLong, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType, ErrorType.Validation);
}
[Fact]
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryPathPartCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathPartCatalogTests
{
private readonly MusicLibraryPathPartCatalog _sut = new();
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Music, result);
}
[Fact]
public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions()
{
// Act
IReadOnlyList<LibraryPathPartDefinition> result = _sut.GetPartDefinitions();
// Assert
Assert.Equal(10, result.Count);
Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind);
Assert.Equal(LibraryPathValueType.None, result[0].ValueType);
Assert.Equal(string.Empty, result[0].DefaultRepresentation);
Assert.False(result[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(LibraryPathValueType.None, result[1].ValueType);
Assert.Equal(string.Empty, result[1].DefaultRepresentation);
Assert.False(result[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Artist, result[2].Kind);
Assert.Equal(LibraryPathValueType.Text, result[2].ValueType);
Assert.Equal("{0}", result[2].DefaultRepresentation);
Assert.False(result[2].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseType, result[3].Kind);
Assert.Equal(LibraryPathValueType.Enum, result[3].ValueType);
Assert.Equal("{0}", result[3].DefaultRepresentation);
Assert.False(result[3].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
Assert.Equal(LibraryPathValueType.Year, result[4].ValueType);
Assert.Equal("{0}", result[4].DefaultRepresentation);
Assert.False(result[4].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseName, result[5].Kind);
Assert.Equal(LibraryPathValueType.Text, result[5].ValueType);
Assert.Equal("{0}", result[5].DefaultRepresentation);
Assert.False(result[5].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackNumber, result[6].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType);
Assert.Equal("{0:00}", result[6].DefaultRepresentation);
Assert.False(result[6].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackName, result[7].Kind);
Assert.Equal(LibraryPathValueType.Text, result[7].ValueType);
Assert.Equal("{0}", result[7].DefaultRepresentation);
Assert.False(result[7].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Extension, result[8].Kind);
Assert.Equal(LibraryPathValueType.Text, result[8].ValueType);
Assert.Equal("{0}", result[8].DefaultRepresentation);
Assert.False(result[8].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[9].ValueType);
Assert.Equal("{0:00}", result[9].DefaultRepresentation);
Assert.True(result[9].IsOptionalByDefault);
}
[Fact]
public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts()
{
// Act
IReadOnlyList<LibraryPathPart> result = _sut.GetDefaultTemplate().Parts;
// Assert
Assert.Equal(16, result.Count);
Assert.Equal(LibraryPathPartKind.Artist, result[0].Kind);
Assert.Equal("{0}", result[0].Representation);
Assert.False(result[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(string.Empty, result[1].Representation);
Assert.False(result[1].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseType, result[2].Kind);
Assert.Equal("{0}", result[2].Representation);
Assert.False(result[2].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[3].Kind);
Assert.Equal(string.Empty, result[3].Representation);
Assert.False(result[3].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
Assert.Equal("{0}", result[4].Representation);
Assert.False(result[4].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind);
Assert.Equal(" - ", result[5].Representation);
Assert.False(result[5].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseName, result[6].Kind);
Assert.Equal("{0}", result[6].Representation);
Assert.False(result[6].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[7].Kind);
Assert.Equal(string.Empty, result[7].Representation);
Assert.True(result[7].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind);
Assert.Equal("Disk ", result[8].Representation);
Assert.True(result[8].IsOptional);
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
Assert.Equal("{0:00}", result[9].Representation);
Assert.True(result[9].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[10].Kind);
Assert.Equal(string.Empty, result[10].Representation);
Assert.False(result[10].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackNumber, result[11].Kind);
Assert.Equal("{0:00}", result[11].Representation);
Assert.False(result[11].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[12].Kind);
Assert.Equal(" - ", result[12].Representation);
Assert.False(result[12].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackName, result[13].Kind);
Assert.Equal("{0}", result[13].Representation);
Assert.False(result[13].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[14].Kind);
Assert.Equal(".", result[14].Representation);
Assert.False(result[14].IsOptional);
Assert.Equal(LibraryPathPartKind.Extension, result[15].Kind);
Assert.Equal("{0}", result[15].Representation);
Assert.False(result[15].IsOptional);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryPathMetadata"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathMetadataTests
{
private readonly MusicLibraryPathMetadataFixture _musicLibraryPathMetadataFixture = new();
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
[Fact]
public void FromParsedLibraryPath_WhenAllValuesAreCaptured_ShouldMapAllFields()
{
// Arrange
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"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.Equal("Queen", result.ArtistName.Value);
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
Assert.Equal(1975, result.ReleaseYear.Value);
Assert.Equal("A Night at the Opera", result.ReleaseName.Value);
Assert.Equal(11, result.TrackNumber.Value);
Assert.Equal(1, result.DiscNumber.Value);
Assert.Equal("Bohemian Rhapsody", result.TrackTitle.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsRecognized_ShouldParseItCaseInsensitively()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseType] = "album"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.True(result.ReleaseType.HasValue);
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsNotRecognized_ShouldFallBackToOther()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseType] = "not a release type"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.True(result.ReleaseType.HasValue);
Assert.Equal(MusicReleaseType.Other, result.ReleaseType.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsAbsent_ShouldLeaveItUnset()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.False(result.ReleaseType.HasValue);
}
[Fact]
public void FromParsedLibraryPath_WhenValuesAreAbsent_ShouldLeaveThemUnset()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(includeValues: false);
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.False(result.ArtistName.HasValue);
Assert.False(result.ReleaseType.HasValue);
Assert.False(result.ReleaseYear.HasValue);
Assert.False(result.ReleaseName.HasValue);
Assert.False(result.TrackNumber.HasValue);
Assert.False(result.DiscNumber.HasValue);
Assert.False(result.TrackTitle.HasValue);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create();
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(
artistName: firstMetadata.ArtistName.Value,
releaseType: firstMetadata.ReleaseType.Value,
releaseYear: firstMetadata.ReleaseYear.Value,
releaseName: firstMetadata.ReleaseName.Value,
trackNumber: firstMetadata.TrackNumber.Value,
discNumber: firstMetadata.DiscNumber.Value,
trackTitle: firstMetadata.TrackTitle.Value);
// Assert
Assert.Equal(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentArtistName_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Queen");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Pink Floyd");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseType_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Album);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Single);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseYear_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1975);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1980);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseName_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "A Night at the Opera");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "The Game");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentTrackNumber_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 11);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 12);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentDiscNumber_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 1);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 2);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentTrackTitle_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Bohemian Rhapsody");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Love of My Life");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPart"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartTests
{
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
[Fact]
public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Separator, "/", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Separator, result.Value.Kind);
Assert.Equal(string.Empty, result.Value.Representation);
}
[Fact]
public void Create_WhenKindIsLiteralWithText_ShouldCreateLiteralWithThatRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Literal, result.Value.Kind);
Assert.Equal(" - ", result.Value.Representation);
}
[Theory]
[InlineData(null)] // the representation is absent
[InlineData("")] // the representation is empty
[InlineData(" ")] // the representation is whitespace
public void Create_WhenKindIsNotSeparatorAndRepresentationIsEmpty_ShouldReturnLiteralCannotBeEmptyError(string? representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void Create_WhenTypedPartContainsSinglePlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("{0}", result.Value.Representation);
}
[Fact]
public void Create_WhenTypedPartContainsFixedWidthPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "Disc {0:00}", isOptional: true);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disc {0:00}", result.Value.Representation);
Assert.True(result.Value.IsOptional);
}
[Theory]
[InlineData("no placeholder")] // the mask carries no value placeholder
[InlineData("{0} {0}")] // the mask carries more than one value placeholder
public void Create_WhenTypedPartDoesNotContainExactlyOnePlaceholder_ShouldReturnError(string representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void Create_WhenLiteralContainsNoPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disk ", result.Value.Representation);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Assert
Assert.Equal(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "Artist: {0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentIsOptional_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplate"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateTests
{
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
[Fact]
public void Create_WhenCalledWithParts_ShouldCreateTemplateWithThoseParts()
{
// Arrange
LibraryPathTemplate template = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate result = LibraryPathTemplate.Create(template.Parts);
// Assert
Assert.Equal(template.Parts, result.Parts);
Assert.False(result.IsEmpty);
}
[Fact]
public void Empty_WhenCalled_ShouldCreateTemplateWithoutParts()
{
// Act
LibraryPathTemplate result = LibraryPathTemplate.Empty();
// Assert
Assert.Empty(result.Parts);
Assert.True(result.IsEmpty);
}
[Fact]
public void Create_WhenSourceCollectionIsLaterModified_ShouldNotAffectTheTemplate()
{
// Arrange
List<LibraryPathPart> sourceParts = [.. _libraryPathTemplateFixture.Create().Parts];
int originalCount = sourceParts.Count;
// Act
LibraryPathTemplate template = LibraryPathTemplate.Create(sourceParts);
sourceParts.Clear();
// Assert
Assert.Equal(originalCount, template.Parts.Count);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create(firstTemplate.Parts);
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WithDifferentParts_ShouldReturnFalse()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate secondTemplate = _libraryPathTemplateFixture.Create();
// Assert
Assert.NotEqual(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WhenBothTemplatesAreEmpty_ShouldReturnTrue()
{
// Act
LibraryPathTemplate firstTemplate = LibraryPathTemplate.Empty();
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Empty();
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
}
@@ -0,0 +1,497 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
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;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplateService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateServiceTests
{
private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For<ILibraryPathPartCatalog>();
private readonly LibraryPathTemplateService _sut;
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplateServiceTests"/> class.
/// </summary>
public LibraryPathTemplateServiceTests()
{
_mockCatalog.SupportedLibraryType.Returns(LibraryType.Music);
_sut = new LibraryPathTemplateService([_mockCatalog]);
}
[Fact]
public void GetDefaultTemplate_WhenCatalogExists_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Music);
// Assert
Assert.Equal(defaultTemplate, result);
}
[Fact]
public void GetDefaultTemplate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnAnEmptyTemplate()
{
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Book);
// Assert
Assert.True(result.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmpty_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
SetupCatalog();
LibraryPathTemplate defaultTemplate = CreateMusicTemplate();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, []);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(defaultTemplate, result.Value);
_mockCatalog.Received(1).GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmptyAndNoCatalogExists_ShouldReturnAnEmptyTemplate()
{
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, []);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotEmpty_ShouldReturnATemplateWithThoseParts()
{
// Arrange
SetupCatalog();
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [providedPart]);
// Assert
Assert.False(result.IsFailure);
LibraryPathPart pathPart = Assert.Single(result.Value.Parts);
Assert.Equal(LibraryPathPartKind.Artist, pathPart.Kind);
Assert.Equal("{0}", pathPart.Representation);
Assert.False(pathPart.IsOptional);
_mockCatalog.DidNotReceive().GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathPart releaseNamePart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [releaseNamePart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ResolveTemplate_WhenNoCatalogExistsForTheLibraryTypeAndPartsAreProvided_ShouldReturnNotSupportedError()
{
// Arrange
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, [artistPart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenTemplateIsEmpty_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, CreateMusicTemplate());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenPartKindIsNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(definitions:
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}")
]);
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenAllPartKindsAreSupportedByTheCatalog_ShouldReturnSuccess()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.False(result.IsFailure);
}
[Theory]
[InlineData("")] // the relative path is empty
[InlineData(" ")] // the relative path is whitespace
public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath)
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenTemplateIsEmpty_ShouldReturnNull()
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError()
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Parse_WhenPathMatchesTheTemplate_ShouldReturnTheCapturedValues()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
ParsedLibraryPath parsedPath = result.Value!;
Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value);
Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value);
Assert.Equal("mp3", parsedPath.GetString(LibraryPathPartKind.Extension).Value);
}
[Fact]
public void Parse_WhenPathDoesNotMatchTheTemplate_ShouldReturnNull()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenIntegerPartHasAFixedWidth_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(7, result.Value!.GetInt(LibraryPathPartKind.TrackNumber).Value);
}
[Fact]
public void Parse_WhenIntegerPartDoesNotMatchTheFixedWidth_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenYearPartHasAFourDigitValue_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1973, result.Value!.GetInt(LibraryPathPartKind.ReleaseYear).Value);
}
[Fact]
public void Parse_WhenYearPartDoesNotHaveAFourDigitValue_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "73", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenAnOptionalRunIsAbsent_ShouldStillMatchThePath()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
Assert.False(result.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
}
[Fact]
public void Parse_WhenAnOptionalRunIsPresent_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(2, result.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
}
[Fact]
public void Parse_WhenTheSameKindAppearsMoreThanOnce_ShouldKeepTheFirstCapture()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Author, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Title, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Title, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Tolkien", result.Value!.GetString(LibraryPathPartKind.Author).Value);
}
/// <summary>
/// Sets up the mock catalog to return a music-like set of part definitions and a default template.
/// </summary>
/// <param name="definitions">Optional. The part definitions the catalog returns. When omitted, a standard music set is used.</param>
private void SetupCatalog(IReadOnlyList<LibraryPathPartDefinition>? definitions = null)
{
_mockCatalog.GetPartDefinitions().Returns(definitions ??
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Extension, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
}
/// <summary>
/// Creates a music-like path template whose parts are all supported by the standard music set of definitions.
/// </summary>
/// <returns>The created path template.</returns>
private LibraryPathTemplate CreateMusicTemplate()
{
return _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackName, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: "."),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Extension, representation: "{0}")
]);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
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 System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPartDefinition"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionTests
{
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Act
LibraryPathPartDefinition definition = new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", isOptionalByDefault: true);
// Assert
Assert.Equal(LibraryPathPartKind.TrackNumber, definition.Kind);
Assert.Equal(LibraryPathValueType.Integer, definition.ValueType);
Assert.Equal("{0:00}", definition.DefaultRepresentation);
Assert.True(definition.IsOptionalByDefault);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Assert
Assert.Equal(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentValueType_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentDefaultRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "Year {0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentIsOptionalByDefault_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: true);
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
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 System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="ParsedLibraryPath"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ParsedLibraryPathTests
{
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
[Fact]
public void Create_WhenCalledWithValues_ShouldExposeThoseValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
// Act
ParsedLibraryPath result = ParsedLibraryPath.Create(values);
// Assert
Assert.Equal(2, result.Values.Count);
Assert.Equal("Pink Floyd", result.Values[LibraryPathPartKind.Artist]);
Assert.Equal("Time", result.Values[LibraryPathPartKind.TrackName]);
}
[Fact]
public void GetString_WhenKindIsCaptured_ShouldReturnTheTrimmedValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " Pink Floyd "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.True(result.HasValue);
Assert.Equal("Pink Floyd", result.Value);
}
[Fact]
public void GetString_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.TrackName);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "1973"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.True(result.HasValue);
Assert.Equal(1973, result.Value);
}
[Fact]
public void GetInt_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "not a year"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.Equal(values, result);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnACopy()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.NotSame(values, result);
}
[Fact]
public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.TrackName] = "Time",
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Assert
Assert.Equal(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentValues_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentKeys_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Title] = "Pink Floyd"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="BookLibraryPathPartCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookLibraryPathPartCatalogTests
{
private readonly BookLibraryPathPartCatalog _sut = new();
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnBook()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Book, result);
}
[Fact]
public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions()
{
// Act
IReadOnlyList<LibraryPathPartDefinition> result = _sut.GetPartDefinitions();
// Assert
Assert.Equal(8, result.Count);
Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind);
Assert.Equal(LibraryPathValueType.None, result[0].ValueType);
Assert.Equal(string.Empty, result[0].DefaultRepresentation);
Assert.False(result[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(LibraryPathValueType.None, result[1].ValueType);
Assert.Equal(string.Empty, result[1].DefaultRepresentation);
Assert.False(result[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Author, result[2].Kind);
Assert.Equal(LibraryPathValueType.Text, result[2].ValueType);
Assert.Equal("{0}", result[2].DefaultRepresentation);
Assert.False(result[2].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Title, result[3].Kind);
Assert.Equal(LibraryPathValueType.Text, result[3].ValueType);
Assert.Equal("{0}", result[3].DefaultRepresentation);
Assert.False(result[3].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Series, result[4].Kind);
Assert.Equal(LibraryPathValueType.Text, result[4].ValueType);
Assert.Equal("{0}", result[4].DefaultRepresentation);
Assert.True(result[4].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.SeriesNumber, result[5].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[5].ValueType);
Assert.Equal("{0}", result[5].DefaultRepresentation);
Assert.True(result[5].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.BookId, result[6].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType);
Assert.Equal("{0}", result[6].DefaultRepresentation);
Assert.False(result[6].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Extension, result[7].Kind);
Assert.Equal(LibraryPathValueType.Text, result[7].ValueType);
Assert.Equal("{0}", result[7].DefaultRepresentation);
Assert.False(result[7].IsOptionalByDefault);
}
[Fact]
public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts()
{
// Act
IReadOnlyList<LibraryPathPart> result = _sut.GetDefaultTemplate().Parts;
// Assert
Assert.Equal(12, result.Count);
Assert.Equal(LibraryPathPartKind.Author, result[0].Kind);
Assert.Equal("{0}", result[0].Representation);
Assert.False(result[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(string.Empty, result[1].Representation);
Assert.False(result[1].IsOptional);
Assert.Equal(LibraryPathPartKind.Title, result[2].Kind);
Assert.Equal("{0}", result[2].Representation);
Assert.False(result[2].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[3].Kind);
Assert.Equal(" (", result[3].Representation);
Assert.False(result[3].IsOptional);
Assert.Equal(LibraryPathPartKind.BookId, result[4].Kind);
Assert.Equal("{0}", result[4].Representation);
Assert.False(result[4].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind);
Assert.Equal(")", result[5].Representation);
Assert.False(result[5].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[6].Kind);
Assert.Equal(string.Empty, result[6].Representation);
Assert.False(result[6].IsOptional);
Assert.Equal(LibraryPathPartKind.Title, result[7].Kind);
Assert.Equal("{0}", result[7].Representation);
Assert.False(result[7].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind);
Assert.Equal(" - ", result[8].Representation);
Assert.False(result[8].IsOptional);
Assert.Equal(LibraryPathPartKind.Author, result[9].Kind);
Assert.Equal("{0}", result[9].Representation);
Assert.False(result[9].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[10].Kind);
Assert.Equal(".", result[10].Representation);
Assert.False(result[10].IsOptional);
Assert.Equal(LibraryPathPartKind.Extension, result[11].Kind);
Assert.Equal("{0}", result[11].Representation);
Assert.False(result[11].IsOptional);
}
}
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests
{
private readonly IQueryHandler<GetLibraryPathTemplatePartsQuery, Result<LibraryPathTemplateCatalogResponse>> _mockHandler;
private readonly GetLibraryPathTemplatePartsEndpoint _sut;
private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new();
private readonly LibraryPathTemplateCatalogResponseFixture _libraryPathTemplateCatalogResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryPathTemplatePartsQuery, Result<LibraryPathTemplateCatalogResponse>>>();
_sut = Factory.Create<GetLibraryPathTemplatePartsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryPathTemplateCatalogResponse()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
LibraryPathTemplateCatalogResponse expectedResponse = _libraryPathTemplateCatalogResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<LibraryPathTemplateCatalogResponse> okResult = Assert.IsType<Ok<LibraryPathTemplateCatalogResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "NotARealLibraryType");
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("Library.UnknownLibraryType", "UnknownLibraryType");
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.NotNull(validationProblemDetails.Instance);
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "UnknownLibraryType" }, validationProblemDetails.Errors["Library.UnknownLibraryType"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryPathTemplatePartsQueryToSender()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Music");
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryPathTemplateCatalogResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryPathTemplatePartsQuery>(query => query.LibraryType == request.LibraryType),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_libraryPathTemplateCatalogResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetLibraryPathTemplatePartsEndpoint _sut;
private readonly GetLibraryPathTemplatePartsRequestFixture _requestFixture = new();
private readonly LibraryPathTemplateCatalogDtoFixture _catalogDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetLibraryPathTemplatePartsEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithCatalog()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create();
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
JsonElement parts = data.GetProperty("parts");
JsonElement defaultTemplateParts = data.GetProperty("defaultTemplateParts");
Assert.Equal(catalog.Parts.Count, parts.GetArrayLength());
Assert.Equal(catalog.DefaultTemplateParts.Count, defaultTemplateParts.GetArrayLength());
JsonElement firstPart = parts[0];
Assert.Equal(catalog.Parts[0].Kind, firstPart.GetProperty("kind").GetString());
Assert.Equal(catalog.Parts[0].ValueType, firstPart.GetProperty("valueType").GetString());
Assert.Equal(catalog.Parts[0].DefaultRepresentation, firstPart.GetProperty("defaultRepresentation").GetString());
Assert.Equal(catalog.Parts[0].IsOptionalByDefault, firstPart.GetProperty("isOptionalByDefault").GetBoolean());
JsonElement firstDefaultTemplatePart = defaultTemplateParts[0];
Assert.Equal(catalog.DefaultTemplateParts[0].Kind, firstDefaultTemplatePart.GetProperty("kind").GetString());
Assert.Equal(catalog.DefaultTemplateParts[0].Representation, firstDefaultTemplatePart.GetProperty("representation").GetString());
Assert.Equal(catalog.DefaultTemplateParts[0].IsOptional, firstDefaultTemplatePart.GetProperty("isOptional").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestCatalogFromApiWithSubstitutedLibraryType()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create(libraryType: "Music");
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", "Music")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create();
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
Arg.Any<string>(),
Arg.Is(cancellationToken));
}
}