diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index d41a53cb..7372692d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -120,12 +120,9 @@ public class AddLibraryCommandHandler : ICommandHandler> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); if (pathTemplatePartsResult.IsFailure) return pathTemplatePartsResult.Errors; - LibraryPathTemplate pathTemplate = command.PathTemplateParts is null - ? _pathTemplateService.GetDefaultTemplate(libraryType) - : LibraryPathTemplate.Create(pathTemplatePartsResult.Value); - Result validatePathTemplateResult = _pathTemplateService.Validate(libraryType, pathTemplate); - if (validatePathTemplateResult.IsFailure) - return validatePathTemplateResult.Errors; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(libraryType, pathTemplatePartsResult.Value); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; // Create a domain library object. Result createLibraryResult = Library.Create( @@ -139,7 +136,7 @@ public class AddLibraryCommandHandler : ICommandHandler> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts(); if (pathTemplatePartsResult.IsFailure) return pathTemplatePartsResult.Errors; - LibraryPathTemplate pathTemplate = command.PathTemplateParts is null - ? _pathTemplateService.GetDefaultTemplate(newLibraryType) - : LibraryPathTemplate.Create(pathTemplatePartsResult.Value); - Result validatePathTemplateResult = _pathTemplateService.Validate(newLibraryType, pathTemplate); - if (validatePathTemplateResult.IsFailure) - return validatePathTemplateResult.Errors; + Result pathTemplateResult = _pathTemplateService.ResolveTemplate(newLibraryType, pathTemplatePartsResult.Value); + if (pathTemplateResult.IsFailure) + return pathTemplateResult.Errors; Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), @@ -153,7 +150,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id))] ); if (createLibraryResult.IsFailure) diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index 498e8d6f..ffff621a 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -20,14 +20,13 @@ public static partial class Errors public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); public static Error CoverFileMustBeAnImage => Error.Validation(description: nameof(CoverFileMustBeAnImage)); - public static Error UnknownLibraryType => Error.Unexpected(description: nameof(UnknownLibraryType)); + public static Error UnknownLibraryType => Error.Forbidden(description: nameof(UnknownLibraryType)); public static Error PathsListCannotBeNull => Error.Validation(description: nameof(PathsListCannotBeNull)); public static Error PathsListCannotBeEmpty => Error.Validation(description: nameof(PathsListCannotBeEmpty)); public static Error TitleCannotBeEmpty => Error.Validation(description: nameof(TitleCannotBeEmpty)); public static Error TitleMustBeMaximum255CharactersLong => Error.Validation(description: nameof(TitleMustBeMaximum255CharactersLong)); public static Error PathTemplateLiteralCannotBeEmpty => Error.Validation(description: nameof(PathTemplateLiteralCannotBeEmpty)); public static Error PathTemplateValuePartMustContainSinglePlaceholder => Error.Validation(description: nameof(PathTemplateValuePartMustContainSinglePlaceholder)); - public static Error PathTemplateCannotContainDuplicateValuePart => Error.Validation(description: nameof(PathTemplateCannotContainDuplicateValuePart)); public static Error PathTemplatePartKindNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplatePartKindNotSupportedForLibraryType)); public static Error PathTemplateIsNotSupportedForLibraryType => Error.Validation(description: nameof(PathTemplateIsNotSupportedForLibraryType)); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index b404e77d..546bfde3 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -77,7 +77,8 @@ public class Library : AggregateRoot public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; } /// - /// Gets the template describing the structure of the media library on disk, always populated, with the ideal structure of the library type as its default. + /// Gets the template describing the structure of the media library on disk, always populated with the effective template: the one specified by the + /// user, or the ideal structure of the library type when none was provided. /// public LibraryPathTemplate PathTemplate { get; private set; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs index 200a21f3..7daf43a9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/ILibraryPathTemplateService.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives; 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; #endregion namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate; @@ -19,6 +20,17 @@ public interface ILibraryPathTemplateService /// The default path template. LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType); + /// + /// Resolves the effective path template of a media library of the provided : the template built from the provided + /// , or the ideal structure of the library type when no parts are provided. + /// + /// The media library type the template belongs to. + /// The parts provided by the user. An empty collection means no template was provided, so the library type default is used. + /// + /// An containing either the resolved path template, or an error. + /// + Result ResolveTemplate(LibraryType libraryType, IReadOnlyList providedParts); + /// /// Validates the provided against the catalog of the provided . /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs index 7f255b6c..ecd9fef5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateService.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives; 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; @@ -23,6 +24,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService private static readonly Regex s_placeholderRegex = new(@"\{0(?::(?0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant); private readonly IReadOnlyList _catalogs; + private readonly ConcurrentDictionary _compiledPatterns = new(); /// /// Initializes a new instance of the class. @@ -43,6 +45,27 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService return ResolveCatalog(libraryType)?.GetDefaultTemplate() ?? LibraryPathTemplate.Empty(); } + /// + /// Resolves the effective path template of a media library of the provided : the template built from the provided + /// , or the ideal structure of the library type when no parts are provided. + /// + /// The media library type the template belongs to. + /// The parts provided by the user. An empty collection means no template was provided, so the library type default is used. + /// + /// An containing either the resolved path template, or an error. + /// + public Result ResolveTemplate(LibraryType libraryType, IReadOnlyList providedParts) + { + // An empty set of parts means the user did not provide a template, so the ideal structure of the library type is used. + LibraryPathTemplate template = providedParts.Count == 0 + ? GetDefaultTemplate(libraryType) + : LibraryPathTemplate.Create(providedParts); + Result validationResult = Validate(libraryType, template); + if (validationResult.IsFailure) + return validationResult.Errors; + return template; + } + /// /// Validates the provided against the catalog of the provided . /// @@ -88,7 +111,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService ILibraryPathPartCatalog catalog = ResolveCatalog(libraryType)!; Dictionary definitions = catalog.GetPartDefinitions() .ToDictionary(definition => definition.Kind); - Regex pattern = BuildPattern(template, definitions, pathSeparator); + Regex pattern = GetCompiledPattern(template, definitions, pathSeparator); Match match = pattern.Match(relativePath); if (!match.Success) return Result.Success(null); @@ -123,13 +146,27 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService } /// - /// Builds the regular expression that matches the provided . + /// Gets the compiled regular expression that matches the provided , building and compiling it only once per distinct + /// pattern, so that scanning a library does not pay the cost of compiling the same pattern once per file. /// /// The path template to compile. /// The available part definitions of the template's library type. /// The character used to separate path segments on the current platform. /// The compiled regular expression. - private static Regex BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary definitions, char pathSeparator) + private Regex GetCompiledPattern(LibraryPathTemplate template, IReadOnlyDictionary definitions, char pathSeparator) + { + string patternText = BuildPattern(template, definitions, pathSeparator); + return _compiledPatterns.GetOrAdd(patternText, pattern => new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant)); + } + + /// + /// Builds the regular expression text that matches the provided . + /// + /// The path template to compile. + /// The available part definitions of the template's library type. + /// The character used to separate path segments on the current platform. + /// The regular expression text. + private static string BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary definitions, char pathSeparator) { StringBuilder patternBuilder = new("^"); int index = 0; @@ -153,7 +190,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService patternBuilder.Append(runBuilder); } patternBuilder.Append('$'); - return new Regex(patternBuilder.ToString(), RegexOptions.Compiled | RegexOptions.CultureInvariant); + return patternBuilder.ToString(); } /// diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index 32ac9e8a..5adbfcdc 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -114,6 +114,30 @@ public class AddLibraryEndpointSummary : Summary +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartDto Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartDto( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index 59e312cd..9eefde82 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -17,6 +17,7 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Ma public class LibraryEntityFixture { private readonly LibraryContentLocationEntityFixture _libraryContentLocationEntityFixture = new(); + private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new(); /// /// Creates a random valid . @@ -34,6 +35,8 @@ public class LibraryEntityFixture /// Whether unchanged directories should be skipped during a scan or not. /// Optional. The fingerprint of the metadata provider configuration of the media library. /// Optional. The fingerprint of the artwork provider configuration of the media library. + /// Optional. The ordered parts of the path template of the media library. + /// Optional. The fingerprint of the path template of the media library. /// The created media library entity. public LibraryEntity Create( Guid? id = null, @@ -48,7 +51,9 @@ public class LibraryEntityFixture bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false, string? metadataProvidersConfigurationFingerprint = null, - string? artworkProvidersConfigurationFingerprint = null) + string? artworkProvidersConfigurationFingerprint = null, + IEnumerable? pathTemplateParts = null, + string? pathTemplateFingerprint = null) { return new Faker() .CustomInstantiator(f => new LibraryEntity @@ -59,6 +64,7 @@ public class LibraryEntityFixture CoverImage = default, LibraryType = default, ContentLocations = [], + PathTemplateParts = [], LibraryScans = [], IsEnabled = isEnabled, IsLocked = isLocked, @@ -67,6 +73,7 @@ public class LibraryEntityFixture ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, MetadataProvidersConfigurationFingerprint = metadataProvidersConfigurationFingerprint, ArtworkProvidersConfigurationFingerprint = artworkProvidersConfigurationFingerprint, + PathTemplateFingerprint = pathTemplateFingerprint, CreatedOnUtc = default, CreatedBy = default, UpdatedOnUtc = null, @@ -80,6 +87,7 @@ public class LibraryEntityFixture IEnumerable paths = contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath()]; return [.. paths.Select(path => _libraryContentLocationEntityFixture.Create(path: path))]; }) + .RuleFor(library => library.PathTemplateParts, f => pathTemplateParts is null ? [] : [.. pathTemplateParts]) .RuleFor(library => library.CreatedOnUtc, f => f.Date.Past()) .RuleFor(library => library.CreatedBy, f => f.Random.Guid()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs new file mode 100644 index 00000000..bdc0c908 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryPathTemplatePartEntityFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The zero based position of the part in the path template. + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartEntity Create( + int? position = null, + LibraryPathPartKind? kind = null, + string? representation = null, + bool isOptional = false) + { + return new Faker() + .CustomInstantiator(f => new LibraryPathTemplatePartEntity + { + Position = position ?? 0, + Kind = default, + Representation = default!, + IsOptional = isOptional + }) + .RuleFor(part => part.Kind, f => kind ?? f.PickRandom()) + .RuleFor(part => part.Representation, f => representation ?? "{0}") + .Generate(); + } + + /// + /// Creates a list of instances with sequential positions. + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs new file mode 100644 index 00000000..79b242d9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsQueryFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsQuery Create(string? libraryType = null) + { + return new GetLibraryPathTemplatePartsQuery(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs new file mode 100644 index 00000000..d8e865c3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestFixture.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsRequest Create(string? libraryType = null) + { + return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs new file mode 100644 index 00000000..caa489ed --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/LibraryPathTemplatePartRequestFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartRequest Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartRequest( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs new file mode 100644 index 00000000..7b486d2f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathPartDefinitionResponseFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The value type captured by the path part. + /// Optional. The default representation of the path part. + /// Whether the path part is optional by default. + /// The created . + public LibraryPathPartDefinitionResponse Create( + string? kind = null, + string? valueType = null, + string? defaultRepresentation = null, + bool isOptionalByDefault = false) + { + return new LibraryPathPartDefinitionResponse( + kind ?? "Artist", + valueType ?? "Text", + defaultRepresentation ?? "{0}", + isOptionalByDefault); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs new file mode 100644 index 00000000..fb64c03b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplateCatalogResponseFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateCatalogResponseFixture +{ + private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new(); + private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The path parts that can be used in the path template of the library type. + /// Optional. The ordered parts of the default path template of the library type. + /// Whether the catalog should carry selectable path parts. When , no parts are created. + /// Whether the catalog should carry default template parts. When , no default template parts are created. + /// The created . + public LibraryPathTemplateCatalogResponse Create( + List? parts = null, + List? defaultTemplateParts = null, + bool includeParts = true, + bool includeDefaultTemplateParts = true) + { + return new LibraryPathTemplateCatalogResponse( + includeParts ? (parts ?? _libraryPathPartDefinitionResponseFixture.CreateMany(2)) : [], + includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartResponseFixture.CreateMany(2)) : []); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs new file mode 100644 index 00000000..b68c49c3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryPathTemplatePartResponseFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathTemplatePartResponse Create( + string? kind = null, + string? representation = null, + bool isOptional = false) + { + return new LibraryPathTemplatePartResponse( + kind ?? "Artist", + representation ?? "{0}", + isOptional); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs new file mode 100644 index 00000000..4c6f06ff --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.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; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MusicLibraryPathMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the artist derived from the path. + /// Optional. The type of the release derived from the path. + /// Optional. The release year derived from the path. + /// Optional. The name of the release derived from the path. + /// Optional. The number of the track derived from the path. + /// Optional. The number of the disc the track belongs to, derived from the path. + /// Optional. The title of the track derived from the path. + /// Whether the artist name should be captured. When , the artist name is not captured. + /// Whether the release type should be captured. When , the release type is not captured. + /// Whether the release year should be captured. When , the release year is not captured. + /// Whether the release name should be captured. When , the release name is not captured. + /// Whether the track number should be captured. When , the track number is not captured. + /// Whether the disc number should be captured. When , the disc number is not captured. + /// Whether the track title should be captured. When , the track title is not captured. + /// The created . + public MusicLibraryPathMetadata Create( + string? artistName = null, + MusicReleaseType? releaseType = null, + int? releaseYear = null, + string? releaseName = null, + int? trackNumber = null, + int? discNumber = null, + string? trackTitle = null, + bool includeArtistName = true, + bool includeReleaseType = true, + bool includeReleaseYear = true, + bool includeReleaseName = true, + bool includeTrackNumber = true, + bool includeDiscNumber = true, + bool includeTrackTitle = true) + { + Dictionary values = []; + if (includeArtistName) + values[LibraryPathPartKind.Artist] = artistName ?? _faker.Name.FullName(); + if (includeReleaseType) + values[LibraryPathPartKind.ReleaseType] = (releaseType ?? _faker.PickRandom()).ToString(); + if (includeReleaseYear) + values[LibraryPathPartKind.ReleaseYear] = (releaseYear ?? _faker.Random.Int(1900, 2025)).ToString(); + if (includeReleaseName) + values[LibraryPathPartKind.ReleaseName] = releaseName ?? _faker.Commerce.ProductName(); + if (includeTrackNumber) + values[LibraryPathPartKind.TrackNumber] = (trackNumber ?? _faker.Random.Int(1, 30)).ToString(); + if (includeDiscNumber) + values[LibraryPathPartKind.DiscNumber] = (discNumber ?? _faker.Random.Int(1, 4)).ToString(); + if (includeTrackTitle) + values[LibraryPathPartKind.TrackName] = trackTitle ?? _faker.Commerce.ProductName(); + return MusicLibraryPathMetadata.FromParsedLibraryPath(_parsedLibraryPathFixture.Create(values)); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs new file mode 100644 index 00000000..51b3fed1 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartFixture.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The kind of the path part. + /// Optional. The literal text or the value mask of the path part. When omitted, a representation valid for the resolved kind is generated. + /// Whether the path part can be absent from the path. + /// The created . + public LibraryPathPart Create( + LibraryPathPartKind? kind = null, + string? representation = null, + bool isOptional = false) + { + LibraryPathPartKind resolvedKind = kind ?? _faker.PickRandom(); + string resolvedRepresentation = representation ?? CreateValidRepresentation(resolvedKind); + Result partResult = LibraryPathPart.Create(resolvedKind, resolvedRepresentation, isOptional); + if (partResult.IsFailure) + throw new InvalidOperationException("Failed to create LibraryPathPart: " + string.Join(", ", partResult.Errors)); + return partResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a representation that is valid for the provided . + /// + /// The kind of the path part a representation is created for. + /// The created representation. + private string CreateValidRepresentation(LibraryPathPartKind kind) + { + // A separator renders the platform path separator, so it never carries a representation. + if (kind == LibraryPathPartKind.Separator) + return string.Empty; + // A literal is arbitrary on-disk text between value parts, so it carries no value placeholder. + if (kind == LibraryPathPartKind.Literal) + return _faker.Lorem.Word(); + // A typed part must carry exactly one value placeholder, so that the position of the captured value is unambiguous. + return "{0}"; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs new file mode 100644 index 00000000..a6bbf490 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateFixture +{ + private readonly Faker _faker = new(); + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ordered parts that make up the path template. + /// Whether the template should carry parts. When , an empty template is created. + /// The created . + public LibraryPathTemplate Create( + IEnumerable? parts = null, + bool includeParts = true) + { + if (!includeParts) + return LibraryPathTemplate.Empty(); + return LibraryPathTemplate.Create(parts ?? _libraryPathPartFixture.CreateMany(_faker.Random.Int(1, 4))); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs new file mode 100644 index 00000000..9b2b6ba0 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The kind of the described part. + /// Optional. The value type captured by the described part. + /// Optional. The default representation of the described part. + /// Whether the described part is optional by default. + /// The created . + public LibraryPathPartDefinition Create( + LibraryPathPartKind? kind = null, + LibraryPathValueType? valueType = null, + string? defaultRepresentation = null, + bool isOptionalByDefault = false) + { + return new LibraryPathPartDefinition( + kind ?? _faker.PickRandom(), + valueType ?? _faker.PickRandom(), + defaultRepresentation ?? "{0}", + isOptionalByDefault); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs new file mode 100644 index 00000000..fe6f1ee8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathFixture.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class ParsedLibraryPathFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The captured values, keyed by their part kind. + /// Whether the parsed path should carry captured values. When , an empty set of values is created. + /// The created . + public ParsedLibraryPath Create( + IReadOnlyDictionary? values = null, + bool includeValues = true) + { + if (!includeValues) + return ParsedLibraryPath.Create(new Dictionary()); + return ParsedLibraryPath.Create(values ?? CreateRandomValues()); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } + + /// + /// Creates a bounded set of random captured values. + /// + /// The captured values, keyed by their part kind. + private Dictionary CreateRandomValues() + { + LibraryPathPartKind[] candidateKinds = + [ + LibraryPathPartKind.Artist, + LibraryPathPartKind.ReleaseName, + LibraryPathPartKind.TrackName, + LibraryPathPartKind.Title, + LibraryPathPartKind.Author + ]; + + Dictionary values = []; + foreach (LibraryPathPartKind kind in candidateKinds.Take(_faker.Random.Int(1, candidateKinds.Length))) + values[kind] = _faker.Lorem.Word(); + return values; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs new file mode 100644 index 00000000..57ace7bd --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathPartDefinitionDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartDefinitionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional kind of the path part. + /// Optional value type captured by the path part. + /// Optional default representation of the path part. + /// Optional value indicating whether the path part is optional by default. + /// A configured instance. + public LibraryPathPartDefinitionDto Create( + string? kind = null, + string? valueType = null, + string? defaultRepresentation = null, + bool? isOptionalByDefault = null) + { + return new LibraryPathPartDefinitionDto + { + Kind = kind ?? _faker.Random.Word(), + ValueType = valueType ?? _faker.Random.Word(), + DefaultRepresentation = defaultRepresentation ?? "{0}", + IsOptionalByDefault = isOptionalByDefault ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs new file mode 100644 index 00000000..92963aca --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplateCatalogDtoFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateCatalogDtoFixture +{ + private readonly LibraryPathPartDefinitionDtoFixture _libraryPathPartDefinitionDtoFixture = new(); + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional path parts that can be used in the path template of the library type. + /// Optional ordered parts of the default path template of the library type. + /// Whether the catalog should carry selectable path parts. When , the parts are forced to an empty collection. + /// Whether the catalog should carry default template parts. When , the default template parts are forced to an empty collection. + /// A configured instance. + public LibraryPathTemplateCatalogDto Create( + List? parts = null, + List? defaultTemplateParts = null, + bool includeParts = true, + bool includeDefaultTemplateParts = true) + { + return new LibraryPathTemplateCatalogDto + { + Parts = includeParts ? (parts ?? _libraryPathPartDefinitionDtoFixture.CreateMany(2)) : [], + DefaultTemplateParts = includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartDtoFixture.CreateMany(2)) : [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs new file mode 100644 index 00000000..113c2fa0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryPathTemplatePartDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional kind of the path part. + /// Optional literal text or value mask of the path part. + /// Optional value indicating whether the path part can be absent from the path. + /// A configured instance. + public LibraryPathTemplatePartDto Create( + string? kind = null, + string? representation = null, + bool? isOptional = null) + { + return new LibraryPathTemplatePartDto + { + Kind = kind ?? _faker.Random.Word(), + Representation = representation ?? "{0}", + IsOptional = isOptional ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs new file mode 100644 index 00000000..80ef2935 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Management/GetLibraryPathTemplatePartsRequestFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The media library type whose available path parts are retrieved. + /// The created . + public GetLibraryPathTemplatePartsRequest Create( + string? libraryType = null) + { + return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..621b5c40 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,234 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new(); + private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryPathTemplatePartsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsMusic_ShouldReturnMusicCatalog() + { + // Arrange + List expectedParts = GetExpectedMusicParts(); + List expectedDefaultTemplateParts = GetExpectedMusicDefaultTemplateParts(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Music"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Equal(10, catalog!.Parts.Count); + Assert.Equal(16, catalog.DefaultTemplateParts.Count); + Assert.Equal(expectedParts, catalog.Parts); + Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsBook_ShouldReturnBookCatalog() + { + // Arrange + List expectedParts = GetExpectedBookParts(); + List expectedDefaultTemplateParts = GetExpectedBookDefaultTemplateParts(); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Book"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Equal(8, catalog!.Parts.Count); + Assert.Equal(12, catalog.DefaultTemplateParts.Count); + Assert.Equal(expectedParts, catalog.Parts); + Assert.Equal(expectedDefaultTemplateParts, catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeHasNoCatalog_ShouldReturnEmptyCatalog() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/path-template-parts/Movie"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryPathTemplateCatalogResponse? catalog = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(catalog); + Assert.Empty(catalog!.Parts); + Assert.Empty(catalog.DefaultTemplateParts); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsUnknown_ShouldReturnProblemResult() + { + // Arrange + string libraryType = "NotARealLibraryType"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}"); + + // Assert + // An unrecognized library type is a value that is not accepted, so it is reported as forbidden. + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(6, problemDetails!.Count); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("UnknownLibraryType", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Builds the exact path parts expected for a music library, as defined by MusicLibraryPathPartCatalog. + /// + /// The expected path parts, in catalog order. + private List GetExpectedMusicParts() + { + return + [ + _libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Artist", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseType", valueType: "Enum", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseYear", valueType: "Year", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "ReleaseName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "TrackNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "TrackName", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "DiscNumber", valueType: "Integer", defaultRepresentation: "{0:00}", isOptionalByDefault: true) + ]; + } + + /// + /// Builds the exact default template parts expected for a music library, as defined by MusicLibraryPathPartCatalog. + /// + /// The expected default template parts, in template order. + private List GetExpectedMusicDefaultTemplateParts() + { + return + [ + _libraryPathTemplatePartResponseFixture.Create(kind: "Artist", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseType", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseYear", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "ReleaseName", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: "Disk ", isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "DiscNumber", representation: "{0:00}", isOptional: true), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "TrackNumber", representation: "{0:00}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "TrackName", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false) + ]; + } + + /// + /// Builds the exact path parts expected for a book library, as defined by BookLibraryPathPartCatalog. + /// + /// The expected path parts, in catalog order. + private List GetExpectedBookParts() + { + return + [ + _libraryPathPartDefinitionResponseFixture.Create(kind: "Literal", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Separator", valueType: "None", defaultRepresentation: string.Empty, isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Author", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Title", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Series", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: true), + _libraryPathPartDefinitionResponseFixture.Create(kind: "SeriesNumber", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: true), + _libraryPathPartDefinitionResponseFixture.Create(kind: "BookId", valueType: "Integer", defaultRepresentation: "{0}", isOptionalByDefault: false), + _libraryPathPartDefinitionResponseFixture.Create(kind: "Extension", valueType: "Text", defaultRepresentation: "{0}", isOptionalByDefault: false) + ]; + } + + /// + /// Builds the exact default template parts expected for a book library, as defined by BookLibraryPathPartCatalog. + /// + /// The expected default template parts, in template order. + private List GetExpectedBookDefaultTemplateParts() + { + return + [ + _libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " (", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "BookId", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ")", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Separator", representation: string.Empty, isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Title", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: " - ", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Author", representation: "{0}", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Literal", representation: ".", isOptional: false), + _libraryPathTemplatePartResponseFixture.Create(kind: "Extension", representation: "{0}", isOptional: false) + ]; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..d51a5d5a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryPathTemplatePartsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + // A unique X-Forwarded-For isolates rate limiting state per test. + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + } + + [Fact] + public async Task GetLibraryPathTemplateParts_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryType = "Music"; + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/path-template-parts/{libraryType}"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/path-template-parts/{libraryType}", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive SQL injection + [InlineData("Music; rm -rf /")] // command injection + [InlineData("$(whoami)")] // command substitution injection + [InlineData("`whoami`")] // backtick command injection + [InlineData("{0}{1}{0}")] // template/placeholder injection + [InlineData("..\\..\\..\\Windows\\System32\\config\\SAM")] // windows path traversal + [InlineData("%2e%2e%2fetc%2fpasswd")] // encoded path traversal + public async Task GetLibraryPathTemplateParts_WithInjectionInLibraryType_ShouldNotLeakOrError(string maliciousLibraryType) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/path-template-parts/{Uri.EscapeDataString(maliciousLibraryType)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // An unrecognized library type is a value that is not accepted, so it is reported as forbidden, and the response must stay + // generic: the failed request leaks no database, filesystem or framework internals. + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(6, problemDetails!.Count); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("UnknownLibraryType", problemDetails["detail"].GetString()); + Assert.StartsWith("/api/v1/libraries/path-template-parts/", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources. + /// + public void Dispose() + { + _client.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index f3971046..0acc5a9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -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); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs new file mode 100644 index 00000000..7f651edd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/GetLibraryPathTemplatePartsRequestMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs index 44bf69ac..953317fe 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -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 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 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 result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 0a85aec0..d0827892 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -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 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); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs new file mode 100644 index 00000000..8886ae37 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryPathTemplatePartDtoMappingTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplatePartDtoMappingTests +{ + private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new(); + + [Fact] + public void ToDomainParts_WhenPartsIsNull_ShouldReturnEmptyList() + { + // Act + Result> result = LibraryPathTemplatePartDtoMapping.ToDomainParts(null); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public void ToDomainParts_WhenPartsIsEmpty_ShouldReturnEmptyList() + { + // Arrange + List parts = []; + + // Act + Result> 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> 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> 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> 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> 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> 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> 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> 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> result = parts.ToDomainParts(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs index cf7be28a..dd097183 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMappingTests.cs @@ -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); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index 9f94b513..79f310a7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -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; /// @@ -79,8 +86,7 @@ public class AddLibraryCommandHandlerTests _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); - _mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any()).Returns(LibraryPathTemplate.Empty()); - _mockLibraryPathTemplateService.Validate(Arg.Any(), Arg.Any()).Returns(Result.Success); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).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(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [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(), Arg.Any>()).Returns(Result.From(defaultTemplate)); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => parts.Count == 0)); + await _mockLibraryRepository.Received(1).InsertAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + library.PathTemplateParts.First().IsOptional), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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(), Arg.Any>()).Returns(Result.From(resolvedTemplate)); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), cancellationToken: Arg.Any()) + .Returns(Result.From(persistedLibrary)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => + parts.Count == 1 && + parts[0].Kind == LibraryPathPartKind.Artist && + parts[0].Representation == "{0}" && + !parts[0].IsOptional)); + await _mockLibraryRepository.Received(1).InsertAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + !library.PathTemplateParts.First().IsOptional), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting() + { + // Arrange + LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" }; + AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + _mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any(), Arg.Any>()); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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(), Arg.Any>()).Returns(validationError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs index cde654eb..afb9cced 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandValidatorTests.cs @@ -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 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 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 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 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index f4dc5a27..047693d4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -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; /// @@ -82,8 +89,7 @@ public class UpdateLibraryCommandHandlerTests _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); - _mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any()).Returns(LibraryPathTemplate.Empty()); - _mockLibraryPathTemplateService.Validate(Arg.Any(), Arg.Any()).Returns(Result.Success); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).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(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [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(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + LibraryPathPart defaultPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: true); + LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(defaultTemplate)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => parts.Count == 0)); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + library.PathTemplateParts.First().IsOptional), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [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(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + LibraryPathPart providedPart = _libraryPathPartFixture.Create( + kind: LibraryPathPartKind.Artist, + representation: "{0}", + isOptional: false); + LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]); + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(Result.From(resolvedTemplate)); + LibraryType expectedLibraryType = Enum.Parse(command.LibraryType!); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockLibraryPathTemplateService.Received(1).ResolveTemplate( + expectedLibraryType, + Arg.Is>(parts => + parts.Count == 1 && + parts[0].Kind == LibraryPathPartKind.Artist && + parts[0].Representation == "{0}" && + !parts[0].IsOptional)); + await _mockLibraryRepository.Received(1).UpdateAsync( + Arg.Is(library => + library.PathTemplateParts.Count == 1 && + library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist && + library.PathTemplateParts.First().Representation == "{0}" && + !library.PathTemplateParts.First().IsOptional), + Arg.Any()); + } + + [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(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError); + _mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any(), Arg.Any>()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [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(), cancellationToken: Arg.Any()) + .Returns(Result.From(existingLibrary)); + Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType; + _mockLibraryPathTemplateService.ResolveTemplate(Arg.Any(), Arg.Any>()).Returns(validationError); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(validationError, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs index f5c025a2..6f77cf71 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandValidatorTests.cs @@ -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 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 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 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 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 result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + [Fact] public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs new file mode 100644 index 00000000..32394ae0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsQueryHandlerTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsQueryHandlerTests() + { + _mockBookCatalog = Substitute.For(); + _mockBookCatalog.SupportedLibraryType.Returns(LibraryType.Book); + _mockBookCatalog.GetPartDefinitions().Returns([]); + _mockBookCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty()); + _mockMusicCatalog = Substitute.For(); + _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 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 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 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 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(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs index 4fc59370..c6e51715 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -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().UseSqlite("Data Source=:memory:").Options); } + /// + /// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits. + /// + private IModel DesignTimeModel => _context.GetService().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 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()); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs index 7c44ef48..0ecb39fb 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -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(); /// /// Initializes a new instance of the 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 result = await _sut.InsertAsync(library, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedLibrary = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id); + Assert.NotNull(addedLibrary); + Assert.Equal("path-template-fingerprint", addedLibrary!.Entity.PathTemplateFingerprint); + + List> partEntries = [.. _mockContext.ChangeTracker.Entries() + .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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + EntityEntry? keptEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, keptPart)); + Assert.NotNull(keptEntry); + Assert.Equal(EntityState.Unchanged, keptEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + Assert.False(retrievedResult.IsFailure); + LibraryEntity retrievedLibrary = Assert.IsType(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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? replacedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart)); + Assert.NotNull(replacedEntry); + Assert.Equal(EntityState.Deleted, replacedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? removedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, removedPart)); + Assert.NotNull(removedEntry); + Assert.Equal(EntityState.Deleted, removedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + EntityEntry? addedEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, addedPart)); + Assert.NotNull(addedEntry); + Assert.Equal(EntityState.Added, addedEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(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 result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + Assert.DoesNotContain( + _mockContext.ChangeTracker.Entries(), + entityEntry => entityEntry.State == EntityState.Added || entityEntry.State == EntityState.Deleted); + + EntityEntry? firstEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, firstPart)); + Assert.NotNull(firstEntry); + Assert.Equal(EntityState.Unchanged, firstEntry!.State); + + EntityEntry? secondEntry = _mockContext.ChangeTracker.Entries() + .SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, secondPart)); + Assert.NotNull(secondEntry); + Assert.Equal(EntityState.Unchanged, secondEntry!.State); + + Result retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None); + LibraryEntity retrievedLibrary = Assert.IsType(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 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); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs index 4f2edd5c..a2c9a6e0 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -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] diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs new file mode 100644 index 00000000..13a273f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/Services/PathTemplate/MusicLibraryPathPartCatalogTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 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); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs new file mode 100644 index 00000000..aae8ca7b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/MusicLibraryAggregate/ValueObjects/MusicLibraryPathMetadataTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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.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.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.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.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); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs new file mode 100644 index 00000000..0617d1bd --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathPartTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathPartTests +{ + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + + [Fact] + public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation() + { + // Act + Result 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 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 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 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 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 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 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); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs new file mode 100644 index 00000000..e9a51976 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryPathTemplateTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs new file mode 100644 index 00000000..9ebc9bb7 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/PathTemplate/LibraryPathTemplateServiceTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryPathTemplateServiceTests +{ + private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For(); + private readonly LibraryPathTemplateService _sut; + private readonly LibraryPathPartFixture _libraryPathPartFixture = new(); + private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new(); + private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + 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 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 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 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 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 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 result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty()); + + // Assert + Assert.False(result.IsFailure); + } + + [Fact] + public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess() + { + // Act + Result result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty()); + + // Assert + Assert.False(result.IsFailure); + } + + [Fact] + public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError() + { + // Act + Result 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 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 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 result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/'); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public void Parse_WhenTemplateIsEmpty_ShouldReturnNull() + { + // Act + Result 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 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 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 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 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 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 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 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 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 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 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); + } + + /// + /// Sets up the mock catalog to return a music-like set of part definitions and a default template. + /// + /// Optional. The part definitions the catalog returns. When omitted, a standard music set is used. + private void SetupCatalog(IReadOnlyList? 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}") + ]); + } + + /// + /// Creates a music-like path template whose parts are all supported by the standard music set of definitions. + /// + /// The created path template. + 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}") + ]); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs new file mode 100644 index 00000000..7a34ae0d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/LibraryPathPartDefinitionTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs new file mode 100644 index 00000000..cd0e3197 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ParsedLibraryPathTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ParsedLibraryPathTests +{ + private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new(); + + [Fact] + public void Create_WhenCalledWithValues_ShouldExposeThoseValues() + { + // Arrange + Dictionary 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.Artist] = " Pink Floyd " + }); + + // Act + Optional 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.Artist] = "Pink Floyd" + }); + + // Act + Optional result = parsedPath.GetString(LibraryPathPartKind.TrackName); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = " " + }); + + // Act + Optional result = parsedPath.GetString(LibraryPathPartKind.Artist); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseYear] = "1973" + }); + + // Act + Optional 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.Artist] = "Pink Floyd" + }); + + // Act + Optional result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue() + { + // Arrange + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.ReleaseYear] = "not a year" + }); + + // Act + Optional result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear); + + // Assert + Assert.False(result.HasValue); + } + + [Fact] + public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues() + { + // Arrange + Dictionary values = new() + { + [LibraryPathPartKind.Artist] = "Pink Floyd", + [LibraryPathPartKind.TrackName] = "Time" + }; + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values); + + // Act + IReadOnlyDictionary result = parsedPath.ToDictionary(); + + // Assert + Assert.Equal(values, result); + } + + [Fact] + public void ToDictionary_WhenCalled_ShouldReturnACopy() + { + // Arrange + Dictionary values = new() + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }; + ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values); + + // Act + IReadOnlyDictionary result = parsedPath.ToDictionary(); + + // Assert + Assert.NotSame(values, result); + } + + [Fact] + public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue() + { + // Arrange + ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd", + [LibraryPathPartKind.TrackName] = "Time" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [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.Artist] = "Pink Floyd" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Queen" + }); + + // Assert + Assert.NotEqual(firstPath, secondPath); + } + + [Fact] + public void Equals_WithDifferentKeys_ShouldReturnFalse() + { + // Arrange + ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Artist] = "Pink Floyd" + }); + + // Act + ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary + { + [LibraryPathPartKind.Title] = "Pink Floyd" + }); + + // Assert + Assert.NotEqual(firstPath, secondPath); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs new file mode 100644 index 00000000..8316f980 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/PathTemplate/BookLibraryPathPartCatalogTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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 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 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); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..47739d93 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetLibraryPathTemplatePartsEndpoint _sut; + private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new(); + private readonly LibraryPathTemplateCatalogResponseFixture _libraryPathTemplateCatalogResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_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(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(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(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(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(), Arg.Any()) + .Returns(Result.From(_libraryPathTemplateCatalogResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryType == request.LibraryType), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_libraryPathTemplateCatalogResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs new file mode 100644 index 00000000..16df05b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/Management/GetLibraryPathTemplateParts/GetLibraryPathTemplatePartsEndpointTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryPathTemplatePartsEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetLibraryPathTemplatePartsEndpoint _sut; + private readonly GetLibraryPathTemplatePartsRequestFixture _requestFixture = new(); + private readonly LibraryPathTemplateCatalogDtoFixture _catalogDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryPathTemplatePartsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithCatalog() + { + // Arrange + GetLibraryPathTemplatePartsRequest request = _requestFixture.Create(); + LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .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(Arg.Any(), Arg.Any()) + .Returns(catalog); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", "Music")), + Arg.Any()); + } + + [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(Arg.Any(), Arg.Any()) + .Returns(catalog); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } +}