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

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

No files matched your search

@@ -120,12 +120,9 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
Result<IReadOnlyList<LibraryPathPart>> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts();
if (pathTemplatePartsResult.IsFailure)
return pathTemplatePartsResult.Errors;
LibraryPathTemplate pathTemplate = command.PathTemplateParts is null
? _pathTemplateService.GetDefaultTemplate(libraryType)
: LibraryPathTemplate.Create(pathTemplatePartsResult.Value);
Result<Success> validatePathTemplateResult = _pathTemplateService.Validate(libraryType, pathTemplate);
if (validatePathTemplateResult.IsFailure)
return validatePathTemplateResult.Errors;
Result<LibraryPathTemplate> pathTemplateResult = _pathTemplateService.ResolveTemplate(libraryType, pathTemplatePartsResult.Value);
if (pathTemplateResult.IsFailure)
return pathTemplateResult.Errors;
// Create a domain library object.
Result<Library> createLibraryResult = Library.Create(
@@ -139,7 +136,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
command.CanDownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
pathTemplateResult.Value,
[]
);
@@ -134,12 +134,9 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
Result<IReadOnlyList<LibraryPathPart>> pathTemplatePartsResult = command.PathTemplateParts.ToDomainParts();
if (pathTemplatePartsResult.IsFailure)
return pathTemplatePartsResult.Errors;
LibraryPathTemplate pathTemplate = command.PathTemplateParts is null
? _pathTemplateService.GetDefaultTemplate(newLibraryType)
: LibraryPathTemplate.Create(pathTemplatePartsResult.Value);
Result<Success> validatePathTemplateResult = _pathTemplateService.Validate(newLibraryType, pathTemplate);
if (validatePathTemplateResult.IsFailure)
return validatePathTemplateResult.Errors;
Result<LibraryPathTemplate> pathTemplateResult = _pathTemplateService.ResolveTemplate(newLibraryType, pathTemplatePartsResult.Value);
if (pathTemplateResult.IsFailure)
return pathTemplateResult.Errors;
Result<Library> createLibraryResult = Library.Create(
LibraryId.Create(command.Id),
@@ -153,7 +150,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
command.CanDownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
pathTemplate,
pathTemplateResult.Value,
[.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))]
);
if (createLibraryResult.IsFailure)
@@ -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));
}
@@ -77,7 +77,8 @@ public class Library : AggregateRoot<LibraryId>
public bool ShouldSkipUnchangedDirectoriesDuringScan { get; private set; }
/// <summary>
/// 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.
/// </summary>
public LibraryPathTemplate PathTemplate { get; private set; }
@@ -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
/// <returns>The default path template.</returns>
LibraryPathTemplate GetDefaultTemplate(LibraryType libraryType);
/// <summary>
/// Resolves the effective path template of a media library of the provided <paramref name="libraryType"/>: the template built from the provided
/// <paramref name="providedParts"/>, or the ideal structure of the library type when no parts are provided.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="providedParts">The parts provided by the user. An empty collection means no template was provided, so the library type default is used.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the resolved path template, or an error.
/// </returns>
Result<LibraryPathTemplate> ResolveTemplate(LibraryType libraryType, IReadOnlyList<LibraryPathPart> providedParts);
/// <summary>
/// Validates the provided <paramref name="template"/> against the catalog of the provided <paramref name="libraryType"/>.
/// </summary>
@@ -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(?::(?<width>0+))?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IReadOnlyList<ILibraryPathPartCatalog> _catalogs;
private readonly ConcurrentDictionary<string, Regex> _compiledPatterns = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplateService"/> class.
@@ -43,6 +45,27 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
return ResolveCatalog(libraryType)?.GetDefaultTemplate() ?? LibraryPathTemplate.Empty();
}
/// <summary>
/// Resolves the effective path template of a media library of the provided <paramref name="libraryType"/>: the template built from the provided
/// <paramref name="providedParts"/>, or the ideal structure of the library type when no parts are provided.
/// </summary>
/// <param name="libraryType">The media library type the template belongs to.</param>
/// <param name="providedParts">The parts provided by the user. An empty collection means no template was provided, so the library type default is used.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the resolved path template, or an error.
/// </returns>
public Result<LibraryPathTemplate> ResolveTemplate(LibraryType libraryType, IReadOnlyList<LibraryPathPart> 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<Success> validationResult = Validate(libraryType, template);
if (validationResult.IsFailure)
return validationResult.Errors;
return template;
}
/// <summary>
/// Validates the provided <paramref name="template"/> against the catalog of the provided <paramref name="libraryType"/>.
/// </summary>
@@ -88,7 +111,7 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
ILibraryPathPartCatalog catalog = ResolveCatalog(libraryType)!;
Dictionary<LibraryPathPartKind, LibraryPathPartDefinition> 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<ParsedLibraryPath?>.Success(null);
@@ -123,13 +146,27 @@ public sealed class LibraryPathTemplateService : ILibraryPathTemplateService
}
/// <summary>
/// Builds the regular expression that matches the provided <paramref name="template"/>.
/// Gets the compiled regular expression that matches the provided <paramref name="template"/>, 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.
/// </summary>
/// <param name="template">The path template to compile.</param>
/// <param name="definitions">The available part definitions of the template's library type.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>The compiled regular expression.</returns>
private static Regex BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary<LibraryPathPartKind, LibraryPathPartDefinition> definitions, char pathSeparator)
private Regex GetCompiledPattern(LibraryPathTemplate template, IReadOnlyDictionary<LibraryPathPartKind, LibraryPathPartDefinition> definitions, char pathSeparator)
{
string patternText = BuildPattern(template, definitions, pathSeparator);
return _compiledPatterns.GetOrAdd(patternText, pattern => new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant));
}
/// <summary>
/// Builds the regular expression text that matches the provided <paramref name="template"/>.
/// </summary>
/// <param name="template">The path template to compile.</param>
/// <param name="definitions">The available part definitions of the template's library type.</param>
/// <param name="pathSeparator">The character used to separate path segments on the current platform.</param>
/// <returns>The regular expression text.</returns>
private static string BuildPattern(LibraryPathTemplate template, IReadOnlyDictionary<LibraryPathPartKind, LibraryPathPartDefinition> 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();
}
/// <summary>
@@ -114,6 +114,30 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
}
);
Response(403, "The request failed because the authenticated user is not allowed to manage media libraries, or because the request carried an unsupported library type.", "application/problem+json",
example: new[]
{
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Forbidden",
status = 403,
detail = "UnknownLibraryType",
instance = "/api/v1/libraries",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
Response(422, "The request did not pass validation checks.", "application/problem+json",
example: new
{
@@ -128,7 +152,6 @@ public class AddLibraryEndpointSummary : Summary<AddLibraryEndpoint, AddLibraryR
"General.Validation", new[]
{
"LibraryTypeCannotBeNull",
"UnknownLibraryType",
"PathsListCannotBeNull",
"PathsListCannotBeEmpty",
"PathCannotBeEmpty",
@@ -118,15 +118,27 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
}
);
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
example: new
Response(403, "The request failed because the authenticated user is not allowed to manage the media library, or because the request carried an unsupported library type.", "application/problem+json",
example: new[]
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{id}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Failure",
status = 403,
detail = "NotAuthorized",
instance = "/api/v1/libraries/{id}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
},
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
title = "General.Forbidden",
status = 403,
detail = "UnknownLibraryType",
instance = "/api/v1/libraries/{id}",
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
}
}
);
@@ -158,7 +170,6 @@ public class UpdateLibraryEndpointSummary : Summary<UpdateLibraryEndpoint, Updat
"LibraryIdCannotBeEmpty",
"UserIdCannotBeEmpty",
"LibraryTypeCannotBeNull",
"UnknownLibraryType",
"PathsListCannotBeNull",
"PathsListCannotBeEmpty",
"PathCannotBeEmpty",
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplatePartDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartDtoFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplatePartDto"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="representation">Optional. The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>The created <see cref="LibraryPathTemplatePartDto"/>.</returns>
public LibraryPathTemplatePartDto Create(
string? kind = null,
string? representation = null,
bool isOptional = false)
{
return new LibraryPathTemplatePartDto(
kind ?? "Artist",
representation ?? "{0}",
isOptional);
}
/// <summary>
/// Creates a list of <see cref="LibraryPathTemplatePartDto"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathTemplatePartDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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();
/// <summary>
/// Creates a random valid <see cref="LibraryEntity"/>.
@@ -34,6 +35,8 @@ public class LibraryEntityFixture
/// <param name="shouldSkipUnchangedDirectoriesDuringScan">Whether unchanged directories should be skipped during a scan or not.</param>
/// <param name="metadataProvidersConfigurationFingerprint">Optional. The fingerprint of the metadata provider configuration of the media library.</param>
/// <param name="artworkProvidersConfigurationFingerprint">Optional. The fingerprint of the artwork provider configuration of the media library.</param>
/// <param name="pathTemplateParts">Optional. The ordered parts of the path template of the media library.</param>
/// <param name="pathTemplateFingerprint">Optional. The fingerprint of the path template of the media library.</param>
/// <returns>The created media library entity.</returns>
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<LibraryPathTemplatePartEntity>? pathTemplateParts = null,
string? pathTemplateFingerprint = null)
{
return new Faker<LibraryEntity>()
.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<string> 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();
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplatePartEntity"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartEntityFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplatePartEntity"/>.
/// </summary>
/// <param name="position">Optional. The zero based position of the part in the path template.</param>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="representation">Optional. The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>The created <see cref="LibraryPathTemplatePartEntity"/>.</returns>
public LibraryPathTemplatePartEntity Create(
int? position = null,
LibraryPathPartKind? kind = null,
string? representation = null,
bool isOptional = false)
{
return new Faker<LibraryPathTemplatePartEntity>()
.CustomInstantiator(f => new LibraryPathTemplatePartEntity
{
Position = position ?? 0,
Kind = default,
Representation = default!,
IsOptional = isOptional
})
.RuleFor(part => part.Kind, f => kind ?? f.PickRandom<LibraryPathPartKind>())
.RuleFor(part => part.Representation, f => representation ?? "{0}")
.Generate();
}
/// <summary>
/// Creates a list of <see cref="LibraryPathTemplatePartEntity"/> instances with sequential positions.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathTemplatePartEntity> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(index => Create(position: index))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetLibraryPathTemplatePartsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsQueryFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryPathTemplatePartsQuery"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available path parts are retrieved.</param>
/// <returns>The created <see cref="GetLibraryPathTemplatePartsQuery"/>.</returns>
public GetLibraryPathTemplatePartsQuery Create(string? libraryType = null)
{
return new GetLibraryPathTemplatePartsQuery(libraryType ?? "Music");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryPathTemplatePartsQuery"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryPathTemplatePartsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetLibraryPathTemplatePartsRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryPathTemplatePartsRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available path parts are retrieved.</param>
/// <returns>The created <see cref="GetLibraryPathTemplatePartsRequest"/>.</returns>
public GetLibraryPathTemplatePartsRequest Create(string? libraryType = null)
{
return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryPathTemplatePartsRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryPathTemplatePartsRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplatePartRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplatePartRequest"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="representation">Optional. The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>The created <see cref="LibraryPathTemplatePartRequest"/>.</returns>
public LibraryPathTemplatePartRequest Create(
string? kind = null,
string? representation = null,
bool isOptional = false)
{
return new LibraryPathTemplatePartRequest(
kind ?? "Artist",
representation ?? "{0}",
isOptional);
}
/// <summary>
/// Creates a list of <see cref="LibraryPathTemplatePartRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathTemplatePartRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathPartDefinitionResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionResponseFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryPathPartDefinitionResponse"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="valueType">Optional. The value type captured by the path part.</param>
/// <param name="defaultRepresentation">Optional. The default representation of the path part.</param>
/// <param name="isOptionalByDefault">Whether the path part is optional by default.</param>
/// <returns>The created <see cref="LibraryPathPartDefinitionResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="LibraryPathPartDefinitionResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathPartDefinitionResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplateCatalogResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateCatalogResponseFixture
{
private readonly LibraryPathPartDefinitionResponseFixture _libraryPathPartDefinitionResponseFixture = new();
private readonly LibraryPathTemplatePartResponseFixture _libraryPathTemplatePartResponseFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplateCatalogResponse"/>.
/// </summary>
/// <param name="parts">Optional. The path parts that can be used in the path template of the library type.</param>
/// <param name="defaultTemplateParts">Optional. The ordered parts of the default path template of the library type.</param>
/// <param name="includeParts">Whether the catalog should carry selectable path parts. When <see langword="false"/>, no parts are created.</param>
/// <param name="includeDefaultTemplateParts">Whether the catalog should carry default template parts. When <see langword="false"/>, no default template parts are created.</param>
/// <returns>The created <see cref="LibraryPathTemplateCatalogResponse"/>.</returns>
public LibraryPathTemplateCatalogResponse Create(
List<LibraryPathPartDefinitionResponse>? parts = null,
List<LibraryPathTemplatePartResponse>? defaultTemplateParts = null,
bool includeParts = true,
bool includeDefaultTemplateParts = true)
{
return new LibraryPathTemplateCatalogResponse(
includeParts ? (parts ?? _libraryPathPartDefinitionResponseFixture.CreateMany(2)) : [],
includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartResponseFixture.CreateMany(2)) : []);
}
/// <summary>
/// Creates a list of <see cref="LibraryPathTemplateCatalogResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathTemplateCatalogResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplatePartResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartResponseFixture
{
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplatePartResponse"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="representation">Optional. The literal text or the value mask of the path part.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>The created <see cref="LibraryPathTemplatePartResponse"/>.</returns>
public LibraryPathTemplatePartResponse Create(
string? kind = null,
string? representation = null,
bool isOptional = false)
{
return new LibraryPathTemplatePartResponse(
kind ?? "Artist",
representation ?? "{0}",
isOptional);
}
/// <summary>
/// Creates a list of <see cref="LibraryPathTemplatePartResponse"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<LibraryPathTemplatePartResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicLibraryPathMetadata"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathMetadataFixture
{
private readonly Faker _faker = new();
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
/// <summary>
/// Creates a random valid <see cref="MusicLibraryPathMetadata"/>.
/// </summary>
/// <param name="artistName">Optional. The name of the artist derived from the path.</param>
/// <param name="releaseType">Optional. The type of the release derived from the path.</param>
/// <param name="releaseYear">Optional. The release year derived from the path.</param>
/// <param name="releaseName">Optional. The name of the release derived from the path.</param>
/// <param name="trackNumber">Optional. The number of the track derived from the path.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to, derived from the path.</param>
/// <param name="trackTitle">Optional. The title of the track derived from the path.</param>
/// <param name="includeArtistName">Whether the artist name should be captured. When <see langword="false"/>, the artist name is not captured.</param>
/// <param name="includeReleaseType">Whether the release type should be captured. When <see langword="false"/>, the release type is not captured.</param>
/// <param name="includeReleaseYear">Whether the release year should be captured. When <see langword="false"/>, the release year is not captured.</param>
/// <param name="includeReleaseName">Whether the release name should be captured. When <see langword="false"/>, the release name is not captured.</param>
/// <param name="includeTrackNumber">Whether the track number should be captured. When <see langword="false"/>, the track number is not captured.</param>
/// <param name="includeDiscNumber">Whether the disc number should be captured. When <see langword="false"/>, the disc number is not captured.</param>
/// <param name="includeTrackTitle">Whether the track title should be captured. When <see langword="false"/>, the track title is not captured.</param>
/// <returns>The created <see cref="MusicLibraryPathMetadata"/>.</returns>
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<LibraryPathPartKind, string> values = [];
if (includeArtistName)
values[LibraryPathPartKind.Artist] = artistName ?? _faker.Name.FullName();
if (includeReleaseType)
values[LibraryPathPartKind.ReleaseType] = (releaseType ?? _faker.PickRandom<MusicReleaseType>()).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));
}
/// <summary>
/// Creates multiple <see cref="MusicLibraryPathMetadata"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicLibraryPathMetadata"/> instances.</returns>
public List<MusicLibraryPathMetadata> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathPart"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="LibraryPathPart"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the path part.</param>
/// <param name="representation">Optional. The literal text or the value mask of the path part. When omitted, a representation valid for the resolved kind is generated.</param>
/// <param name="isOptional">Whether the path part can be absent from the path.</param>
/// <returns>The created <see cref="LibraryPathPart"/>.</returns>
public LibraryPathPart Create(
LibraryPathPartKind? kind = null,
string? representation = null,
bool isOptional = false)
{
LibraryPathPartKind resolvedKind = kind ?? _faker.PickRandom<LibraryPathPartKind>();
string resolvedRepresentation = representation ?? CreateValidRepresentation(resolvedKind);
Result<LibraryPathPart> partResult = LibraryPathPart.Create(resolvedKind, resolvedRepresentation, isOptional);
if (partResult.IsFailure)
throw new InvalidOperationException("Failed to create LibraryPathPart: " + string.Join(", ", partResult.Errors));
return partResult.Value;
}
/// <summary>
/// Creates multiple <see cref="LibraryPathPart"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathPart"/> instances.</returns>
public List<LibraryPathPart> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates a representation that is valid for the provided <paramref name="kind"/>.
/// </summary>
/// <param name="kind">The kind of the path part a representation is created for.</param>
/// <returns>The created representation.</returns>
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}";
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplate"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateFixture
{
private readonly Faker _faker = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
/// <summary>
/// Creates a random valid <see cref="LibraryPathTemplate"/>.
/// </summary>
/// <param name="parts">Optional. The ordered parts that make up the path template.</param>
/// <param name="includeParts">Whether the template should carry parts. When <see langword="false"/>, an empty template is created.</param>
/// <returns>The created <see cref="LibraryPathTemplate"/>.</returns>
public LibraryPathTemplate Create(
IEnumerable<LibraryPathPart>? parts = null,
bool includeParts = true)
{
if (!includeParts)
return LibraryPathTemplate.Empty();
return LibraryPathTemplate.Create(parts ?? _libraryPathPartFixture.CreateMany(_faker.Random.Int(1, 4)));
}
/// <summary>
/// Creates multiple <see cref="LibraryPathTemplate"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathTemplate"/> instances.</returns>
public List<LibraryPathTemplate> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathPartDefinition"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="LibraryPathPartDefinition"/>.
/// </summary>
/// <param name="kind">Optional. The kind of the described part.</param>
/// <param name="valueType">Optional. The value type captured by the described part.</param>
/// <param name="defaultRepresentation">Optional. The default representation of the described part.</param>
/// <param name="isOptionalByDefault">Whether the described part is optional by default.</param>
/// <returns>The created <see cref="LibraryPathPartDefinition"/>.</returns>
public LibraryPathPartDefinition Create(
LibraryPathPartKind? kind = null,
LibraryPathValueType? valueType = null,
string? defaultRepresentation = null,
bool isOptionalByDefault = false)
{
return new LibraryPathPartDefinition(
kind ?? _faker.PickRandom<LibraryPathPartKind>(),
valueType ?? _faker.PickRandom<LibraryPathValueType>(),
defaultRepresentation ?? "{0}",
isOptionalByDefault);
}
/// <summary>
/// Creates multiple <see cref="LibraryPathPartDefinition"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathPartDefinition"/> instances.</returns>
public List<LibraryPathPartDefinition> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="ParsedLibraryPath"/> domain value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class ParsedLibraryPathFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="ParsedLibraryPath"/>.
/// </summary>
/// <param name="values">Optional. The captured values, keyed by their part kind.</param>
/// <param name="includeValues">Whether the parsed path should carry captured values. When <see langword="false"/>, an empty set of values is created.</param>
/// <returns>The created <see cref="ParsedLibraryPath"/>.</returns>
public ParsedLibraryPath Create(
IReadOnlyDictionary<LibraryPathPartKind, string>? values = null,
bool includeValues = true)
{
if (!includeValues)
return ParsedLibraryPath.Create(new Dictionary<LibraryPathPartKind, string>());
return ParsedLibraryPath.Create(values ?? CreateRandomValues());
}
/// <summary>
/// Creates multiple <see cref="ParsedLibraryPath"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ParsedLibraryPath"/> instances.</returns>
public List<ParsedLibraryPath> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates a bounded set of random captured values.
/// </summary>
/// <returns>The captured values, keyed by their part kind.</returns>
private Dictionary<LibraryPathPartKind, string> CreateRandomValues()
{
LibraryPathPartKind[] candidateKinds =
[
LibraryPathPartKind.Artist,
LibraryPathPartKind.ReleaseName,
LibraryPathPartKind.TrackName,
LibraryPathPartKind.Title,
LibraryPathPartKind.Author
];
Dictionary<LibraryPathPartKind, string> values = [];
foreach (LibraryPathPartKind kind in candidateKinds.Take(_faker.Random.Int(1, candidateKinds.Length)))
values[kind] = _faker.Lorem.Word();
return values;
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathPartDefinitionDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LibraryPathPartDefinitionDto"/> instance with randomized test data.
/// </summary>
/// <param name="kind">Optional kind of the path part.</param>
/// <param name="valueType">Optional value type captured by the path part.</param>
/// <param name="defaultRepresentation">Optional default representation of the path part.</param>
/// <param name="isOptionalByDefault">Optional value indicating whether the path part is optional by default.</param>
/// <returns>A configured <see cref="LibraryPathPartDefinitionDto"/> instance.</returns>
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()
};
}
/// <summary>
/// Creates multiple <see cref="LibraryPathPartDefinitionDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathPartDefinitionDto"/> instances.</returns>
public List<LibraryPathPartDefinitionDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplateCatalogDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateCatalogDtoFixture
{
private readonly LibraryPathPartDefinitionDtoFixture _libraryPathPartDefinitionDtoFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
/// <summary>
/// Creates a new <see cref="LibraryPathTemplateCatalogDto"/> instance with randomized test data.
/// </summary>
/// <param name="parts">Optional path parts that can be used in the path template of the library type.</param>
/// <param name="defaultTemplateParts">Optional ordered parts of the default path template of the library type.</param>
/// <param name="includeParts">Whether the catalog should carry selectable path parts. When <see langword="false"/>, the parts are forced to an empty collection.</param>
/// <param name="includeDefaultTemplateParts">Whether the catalog should carry default template parts. When <see langword="false"/>, the default template parts are forced to an empty collection.</param>
/// <returns>A configured <see cref="LibraryPathTemplateCatalogDto"/> instance.</returns>
public LibraryPathTemplateCatalogDto Create(
List<LibraryPathPartDefinitionDto>? parts = null,
List<LibraryPathTemplatePartDto>? defaultTemplateParts = null,
bool includeParts = true,
bool includeDefaultTemplateParts = true)
{
return new LibraryPathTemplateCatalogDto
{
Parts = includeParts ? (parts ?? _libraryPathPartDefinitionDtoFixture.CreateMany(2)) : [],
DefaultTemplateParts = includeDefaultTemplateParts ? (defaultTemplateParts ?? _libraryPathTemplatePartDtoFixture.CreateMany(2)) : []
};
}
/// <summary>
/// Creates multiple <see cref="LibraryPathTemplateCatalogDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathTemplateCatalogDto"/> instances.</returns>
public List<LibraryPathTemplateCatalogDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="LibraryPathTemplatePartDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LibraryPathTemplatePartDto"/> instance with randomized test data.
/// </summary>
/// <param name="kind">Optional kind of the path part.</param>
/// <param name="representation">Optional literal text or value mask of the path part.</param>
/// <param name="isOptional">Optional value indicating whether the path part can be absent from the path.</param>
/// <returns>A configured <see cref="LibraryPathTemplatePartDto"/> instance.</returns>
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()
};
}
/// <summary>
/// Creates multiple <see cref="LibraryPathTemplatePartDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryPathTemplatePartDto"/> instances.</returns>
public List<LibraryPathTemplatePartDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetLibraryPathTemplatePartsRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="GetLibraryPathTemplatePartsRequest"/>.
/// </summary>
/// <param name="libraryType">Optional. The media library type whose available path parts are retrieved.</param>
/// <returns>The created <see cref="GetLibraryPathTemplatePartsRequest"/>.</returns>
public GetLibraryPathTemplatePartsRequest Create(
string? libraryType = null)
{
return new GetLibraryPathTemplatePartsRequest(libraryType ?? "Music");
}
/// <summary>
/// Creates a list of <see cref="GetLibraryPathTemplatePartsRequest"/>.
/// </summary>
/// <param name="count">The number of elements to create.</param>
/// <returns>The created list.</returns>
public List<GetLibraryPathTemplatePartsRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryPathTemplatePartsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes authenticated API client.
/// </summary>
public async Task InitializeAsync()
{
_client = await _apiFactory.CreateAuthenticatedClientAsync();
}
[Fact]
public async Task GetLibraryPathTemplateParts_WhenLibraryTypeIsMusic_ShouldReturnMusicCatalog()
{
// Arrange
List<LibraryPathPartDefinitionResponse> expectedParts = GetExpectedMusicParts();
List<LibraryPathTemplatePartResponse> 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<LibraryPathTemplateCatalogResponse>(_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<LibraryPathPartDefinitionResponse> expectedParts = GetExpectedBookParts();
List<LibraryPathTemplatePartResponse> 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<LibraryPathTemplateCatalogResponse>(_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<LibraryPathTemplateCatalogResponse>(_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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
}
/// <summary>
/// Builds the exact path parts expected for a music library, as defined by <c>MusicLibraryPathPartCatalog</c>.
/// </summary>
/// <returns>The expected path parts, in catalog order.</returns>
private List<LibraryPathPartDefinitionResponse> 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)
];
}
/// <summary>
/// Builds the exact default template parts expected for a music library, as defined by <c>MusicLibraryPathPartCatalog</c>.
/// </summary>
/// <returns>The expected default template parts, in template order.</returns>
private List<LibraryPathTemplatePartResponse> 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)
];
}
/// <summary>
/// Builds the exact path parts expected for a book library, as defined by <c>BookLibraryPathPartCatalog</c>.
/// </summary>
/// <returns>The expected path parts, in catalog order.</returns>
private List<LibraryPathPartDefinitionResponse> 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)
];
}
/// <summary>
/// Builds the exact default template parts expected for a book library, as defined by <c>BookLibraryPathPartCatalog</c>.
/// </summary>
/// <returns>The expected default template parts, in template order.</returns>
private List<LibraryPathTemplatePartResponse> 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)
];
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
await _apiFactory.RemoveTestUserAsync();
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Disposes the API factory resources.
/// </summary>
public void Dispose()
{
_client.Dispose();
}
}
@@ -16,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class AddMediaLibraryRequestMappingTests
{
private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
@@ -144,4 +145,45 @@ public class AddMediaLibraryRequestMappingTests
Assert.NotNull(result);
Assert.Null(result.CoverImage);
}
[Fact]
public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray()
{
// Arrange
LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.PathTemplateParts);
Assert.Equal(2, result.PathTemplateParts.Length);
Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind);
Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation);
Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional);
Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind);
Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation);
Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional);
}
[Fact]
public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull()
{
// Arrange
AddLibraryRequest request = _addLibraryRequestFixture.Create(pathTemplateParts: null);
// Act
AddLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.PathTemplateParts);
}
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsRequestMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsRequestMappingTests
{
private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new();
[Fact]
public void ToQuery_WhenMappingValidRequest_ShouldMapLibraryType()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Book");
// Act
GetLibraryPathTemplatePartsQuery result = request.ToQuery();
// Assert
Assert.Equal("Book", result.LibraryType);
}
[Theory]
[InlineData("Book")] // a written content library type
[InlineData("Movie")] // a video library type
[InlineData("Music")] // an audio library type
public void ToQuery_WhenMappingDifferentLibraryTypes_ShouldMapLibraryType(string libraryType)
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: libraryType);
// Act
GetLibraryPathTemplatePartsQuery result = request.ToQuery();
// Assert
Assert.Equal(libraryType, result.LibraryType);
}
}
@@ -3,10 +3,14 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
@@ -18,6 +22,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class LibraryEntityMappingTests
{
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
[Fact]
public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly()
@@ -123,4 +128,126 @@ public class LibraryEntityMappingTests
Assert.NotNull(result);
Assert.Null(result.CoverImage);
}
[Fact]
public void ToResponse_WhenLibraryHasPathTemplateParts_ShouldOrderByPositionAndMapProperties()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(
position: 2,
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Literal,
representation: "Various Artists");
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(
position: 1,
kind: LibraryPathPartKind.Separator,
representation: string.Empty);
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [firstPart, secondPart, thirdPart]);
// Act
LibraryResponse result = entity.ToResponse();
// Assert
Assert.Equal(3, result.PathTemplateParts.Count);
Assert.Equal(LibraryPathPartKind.Literal.ToString(), result.PathTemplateParts[0].Kind);
Assert.Equal("Various Artists", result.PathTemplateParts[0].Representation);
Assert.False(result.PathTemplateParts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.PathTemplateParts[1].Kind);
Assert.Equal(string.Empty, result.PathTemplateParts[1].Representation);
Assert.False(result.PathTemplateParts[1].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.PathTemplateParts[2].Kind);
Assert.Equal("{0}", result.PathTemplateParts[2].Representation);
Assert.True(result.PathTemplateParts[2].IsOptional);
}
[Fact]
public void ToDomainEntity_WhenLibraryHasPathTemplateParts_ShouldBuildTemplateFromOrderedParts()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(
position: 1,
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Literal,
representation: "Various Artists");
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
coverImage: "D:/cover.jpg",
pathTemplateParts: [firstPart, secondPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(entity.Id, result.Value.Id.Value);
Assert.Equal(entity.UserId, result.Value.UserId.Value);
Assert.Equal(entity.Title, result.Value.Title);
Assert.Equal(entity.LibraryType, result.Value.LibraryType);
Assert.Equal("D:/cover.jpg", result.Value.CoverImage.Value);
Assert.Equal(2, result.Value.PathTemplate.Parts.Count);
Assert.Equal(LibraryPathPartKind.Literal, result.Value.PathTemplate.Parts[0].Kind);
Assert.Equal("Various Artists", result.Value.PathTemplate.Parts[0].Representation);
Assert.False(result.Value.PathTemplate.Parts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist, result.Value.PathTemplate.Parts[1].Kind);
Assert.Equal("{0}", result.Value.PathTemplate.Parts[1].Representation);
Assert.True(result.Value.PathTemplate.Parts[1].IsOptional);
}
[Fact]
public void ToDomainEntity_WhenStoredTypedPartHasEmptyRepresentation_ShouldReturnPathTemplateLiteralCannotBeEmpty()
{
// Arrange
LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.Artist,
representation: string.Empty);
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [invalidPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void ToDomainEntity_WhenStoredTypedPartHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartEntity invalidPart = _libraryPathTemplatePartEntityFixture.Create(
position: 0,
kind: LibraryPathPartKind.TrackNumber,
representation: "Track");
LibraryEntity entity = _libraryEntityFixture.Create(
title: "My Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplateParts: [invalidPart]);
// Act
Result<Library> result = entity.ToDomainEntity();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
}
@@ -4,7 +4,9 @@ using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
@@ -21,6 +23,8 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class LibraryMappingTests
{
private readonly LibraryFixture _libraryFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
[Fact]
public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly()
@@ -185,4 +189,57 @@ public class LibraryMappingTests
Assert.NotNull(library.ScanIds);
Assert.NotNull(result.LibraryScans);
}
[Fact]
public void ToRepositoryEntity_WhenLibraryHasPathTemplateParts_ShouldMapPartsWithSequentialPositions()
{
// Arrange
LibraryPathPart literalPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Literal,
representation: "Various Artists",
isOptional: false);
LibraryPathPart typedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(parts: [literalPart, typedPart]);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplate: pathTemplate);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
List<LibraryPathTemplatePartEntity> parts = [.. result.PathTemplateParts.OrderBy(part => part.Position)];
Assert.Equal(2, parts.Count);
Assert.Equal(0, parts[0].Position);
Assert.Equal(LibraryPathPartKind.Literal, parts[0].Kind);
Assert.Equal("Various Artists", parts[0].Representation);
Assert.False(parts[0].IsOptional);
Assert.Equal(1, parts[1].Position);
Assert.Equal(LibraryPathPartKind.Artist, parts[1].Kind);
Assert.Equal("{0}", parts[1].Representation);
Assert.True(parts[1].IsOptional);
}
[Fact]
public void ToRepositoryEntity_WhenLibraryHasNoPathTemplateParts_ShouldMapEmptyCollection()
{
// Arrange
LibraryPathTemplate pathTemplate = _libraryPathTemplateFixture.Create(includeParts: false);
Library library = _libraryFixture.Create(
title: "Test Library",
libraryType: LibraryType.Book,
contentLocations: ["C:/Books"],
pathTemplate: pathTemplate);
// Act
LibraryEntity result = library.ToRepositoryEntity();
// Assert
Assert.Empty(result.PathTemplateParts);
}
}
@@ -0,0 +1,204 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplatePartDtoMapping"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplatePartDtoMappingTests
{
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void ToDomainParts_WhenPartsIsNull_ShouldReturnEmptyList()
{
// Act
Result<IReadOnlyList<LibraryPathPart>> result = LibraryPathTemplatePartDtoMapping.ToDomainParts(null);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public void ToDomainParts_WhenPartsIsEmpty_ShouldReturnEmptyList()
{
// Arrange
List<LibraryPathTemplatePartDto> parts = [];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value);
}
[Fact]
public void ToDomainParts_WhenPartsAreValid_ShouldMapKindRepresentationAndIsOptional()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
LibraryPathTemplatePartDto[] parts = [literalPart, typedPart];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Equal(2, result.Value.Count);
Assert.Equal(LibraryPathPartKind.Literal, result.Value[0].Kind);
Assert.Equal("Various Artists", result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Artist, result.Value[1].Kind);
Assert.Equal("{0}", result.Value[1].Representation);
Assert.True(result.Value[1].IsOptional);
}
[Fact]
public void ToDomainParts_WhenPartIsSeparator_ShouldMapWithEmptyRepresentation()
{
// Arrange
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: @"\",
isOptional: false);
LibraryPathTemplatePartDto[] parts = [separatorPart];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(LibraryPathPartKind.Separator, result.Value[0].Kind);
Assert.Equal(string.Empty, result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
}
[Fact]
public void ToDomainParts_WhenKindIsUnknown_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: "NotARealLibraryPathPartKind");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenKindIsNull_ShouldReturnPathTemplatePartKindNotSupportedForLibraryType()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = null };
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenKindUsesDifferentCasing_ShouldMapKind()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: "artist",
representation: "{0}",
isOptional: false);
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.False(result.IsFailure);
Assert.Single(result.Value);
Assert.Equal(LibraryPathPartKind.Artist, result.Value[0].Kind);
Assert.Equal("{0}", result.Value[0].Representation);
Assert.False(result.Value[0].IsOptional);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationIsEmpty_ShouldReturnPathTemplateLiteralCannotBeEmpty()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: string.Empty);
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationHasNoPlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "Artist Name");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void ToDomainParts_WhenTypedPartRepresentationHasDuplicatePlaceholder_ShouldReturnPathTemplateValuePartMustContainSinglePlaceholder()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0} - {0}");
LibraryPathTemplatePartDto[] parts = [part];
// Act
Result<IReadOnlyList<LibraryPathPart>> result = parts.ToDomainParts();
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -15,6 +16,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management;
public class UpdateLibraryRequestMappingTests
{
private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new();
private readonly LibraryPathTemplatePartRequestFixture _libraryPathTemplatePartRequestFixture = new();
[Fact]
public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly()
@@ -46,4 +48,45 @@ public class UpdateLibraryRequestMappingTests
Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories);
Assert.Equal(request.ShouldSkipUnchangedDirectoriesDuringScan, result.ShouldSkipUnchangedDirectoriesDuringScan);
}
[Fact]
public void ToCommand_WhenRequestHasPathTemplateParts_ShouldMapToDtoArray()
{
// Arrange
LibraryPathTemplatePartRequest literalPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists",
isOptional: false);
LibraryPathTemplatePartRequest typedPart = _libraryPathTemplatePartRequestFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: true);
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: [literalPart, typedPart]);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.NotNull(result.PathTemplateParts);
Assert.Equal(2, result.PathTemplateParts.Length);
Assert.Equal(literalPart.Kind, result.PathTemplateParts[0].Kind);
Assert.Equal(literalPart.Representation, result.PathTemplateParts[0].Representation);
Assert.Equal(literalPart.IsOptional, result.PathTemplateParts[0].IsOptional);
Assert.Equal(typedPart.Kind, result.PathTemplateParts[1].Kind);
Assert.Equal(typedPart.Representation, result.PathTemplateParts[1].Representation);
Assert.Equal(typedPart.IsOptional, result.PathTemplateParts[1].IsOptional);
}
[Fact]
public void ToCommand_WhenPathTemplatePartsIsNull_ShouldMapToNull()
{
// Arrange
UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(pathTemplateParts: null);
// Act
UpdateLibraryCommand result = request.ToCommand();
// Assert
Assert.Null(result.PathTemplateParts);
}
}
@@ -3,12 +3,14 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
@@ -17,12 +19,14 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -49,6 +53,9 @@ public class AddLibraryCommandHandlerTests
private readonly AddLibraryCommandHandler _sut;
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -79,8 +86,7 @@ public class AddLibraryCommandHandlerTests
_mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<AddLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any<LibraryType>()).Returns(LibraryPathTemplate.Empty());
_mockLibraryPathTemplateService.Validate(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>()).Returns(Result.Success);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
_sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator);
}
@@ -296,4 +302,118 @@ public class AddLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(defaultTemplate));
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts => parts.Count == 0));
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts()
{
// Arrange
LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: false);
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(resolvedTemplate));
LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(persistedLibrary));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts =>
parts.Count == 1 &&
parts[0].Kind == LibraryPathPartKind.Artist &&
parts[0].Representation == "{0}" &&
!parts[0].IsOptional));
await _mockLibraryRepository.Received(1).InsertAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
!library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
_mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>());
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(validationError);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -18,6 +21,7 @@ public class AddLibraryCommandValidatorTests
{
private readonly AddLibraryCommandValidator _validator = new();
private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void Validate_WhenLibraryTypeIsNull_ShouldHaveValidationError()
@@ -201,6 +205,92 @@ public class AddLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
[Fact]
public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError()
{
// Arrange
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation };
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists");
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
AddLibraryCommand command = _addLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
@@ -10,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Plugins;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
@@ -18,6 +20,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
@@ -25,6 +28,7 @@ using NSubstitute;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -51,6 +55,9 @@ public class UpdateLibraryCommandHandlerTests
private readonly UpdateLibraryCommandHandler _sut;
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
private readonly Guid _userId;
/// <summary>
@@ -82,8 +89,7 @@ public class UpdateLibraryCommandHandlerTests
_mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any<Guid>(), Arg.Any<LibraryType>(), Arg.Any<CancellationToken>())
.Returns(Result.Success);
_mockValidator.Validate(Arg.Any<UpdateLibraryCommand>()).Returns([]);
_mockLibraryPathTemplateService.GetDefaultTemplate(Arg.Any<LibraryType>()).Returns(LibraryPathTemplate.Empty());
_mockLibraryPathTemplateService.Validate(Arg.Any<LibraryType>(), Arg.Any<LibraryPathTemplate>()).Returns(Result.Success);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(LibraryPathTemplate.Empty()));
_sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockLibraryPathTemplateService, _mockUnitOfWork, _mockValidator);
}
@@ -422,4 +428,124 @@ public class UpdateLibraryCommandHandlerTests
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsIsNull_ShouldResolveTemplateWithoutParts()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart defaultPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [defaultPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(defaultTemplate));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts => parts.Count == 0));
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplatePartsAreProvided_ShouldBuildTemplateFromProvidedParts()
{
// Arrange
LibraryPathTemplatePartDto providedDto = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}",
isOptional: false);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [providedDto]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathTemplate resolvedTemplate = _libraryPathTemplateFixture.Create(parts: [providedPart]);
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(Result.From(resolvedTemplate));
LibraryType expectedLibraryType = Enum.Parse<LibraryType>(command.LibraryType!);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
_mockLibraryPathTemplateService.Received(1).ResolveTemplate(
expectedLibraryType,
Arg.Is<IReadOnlyList<LibraryPathPart>>(parts =>
parts.Count == 1 &&
parts[0].Kind == LibraryPathPartKind.Artist &&
parts[0].Representation == "{0}" &&
!parts[0].IsOptional));
await _mockLibraryRepository.Received(1).UpdateAsync(
Arg.Is<LibraryEntity>(library =>
library.PathTemplateParts.Count == 1 &&
library.PathTemplateParts.First().Kind == LibraryPathPartKind.Artist &&
library.PathTemplateParts.First().Representation == "{0}" &&
!library.PathTemplateParts.First().IsOptional),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateMappingFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto invalidPart = _libraryPathTemplatePartDtoFixture.Create() with { Kind = "NotARealLibraryPathPartKind" };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [invalidPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
_mockLibraryPathTemplateService.DidNotReceive().ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>());
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenPathTemplateValidationFails_ShouldReturnErrorWithoutPersisting()
{
// Arrange
LibraryPathTemplatePartDto validPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [validPart]);
LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId);
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), cancellationToken: Arg.Any<CancellationToken>())
.Returns(Result.From<LibraryEntity?>(existingLibrary));
Error validationError = DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType;
_mockLibraryPathTemplateService.ResolveTemplate(Arg.Any<LibraryType>(), Arg.Any<IReadOnlyList<LibraryPathPart>>()).Returns(validationError);
// Act
Result<LibraryResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(validationError, result.FirstError);
await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any<LibraryEntity>(), Arg.Any<CancellationToken>());
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
}
}
@@ -1,9 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.Management;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary;
using Lumina.Application.UnitTests.Common.Setup;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -19,6 +22,7 @@ public class UpdateLibraryCommandValidatorTests
{
private readonly UpdateLibraryCommandValidator _validator = new();
private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new();
private readonly LibraryPathTemplatePartDtoFixture _libraryPathTemplatePartDtoFixture = new();
[Fact]
public void Validate_WhenIdIsEmpty_ShouldHaveValidationError()
@@ -256,6 +260,92 @@ public class UpdateLibraryCommandValidatorTests
result.ShouldNotHaveValidationError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
[Fact]
public void Validate_WhenPathTemplatePartsIsNull_ShouldNotHaveValidationError()
{
// Arrange
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: null);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Theory]
[InlineData(null)] // an absent kind
[InlineData("")] // an empty kind
[InlineData(" ")] // a whitespace kind
public void Validate_WhenPathTemplatePartKindIsNullOrEmpty_ShouldHaveValidationError(string? kind)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create() with { Kind = kind };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType);
}
[Theory]
[InlineData(null)] // an absent representation
[InlineData("")] // an empty representation
[InlineData(" ")] // a whitespace representation
public void Validate_WhenNonSeparatorPartRepresentationIsNullOrEmpty_ShouldHaveValidationError(string? representation)
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(kind: nameof(LibraryPathPartKind.Artist)) with { Representation = representation };
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenSeparatorPartRepresentationIsEmpty_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto part = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [part]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveValidationError(Errors.Library.PathTemplateLiteralCannotBeEmpty);
}
[Fact]
public void Validate_WhenPathTemplatePartsAreValid_ShouldNotHaveValidationError()
{
// Arrange
LibraryPathTemplatePartDto literalPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Literal),
representation: "Various Artists");
LibraryPathTemplatePartDto separatorPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Separator),
representation: string.Empty);
LibraryPathTemplatePartDto typedPart = _libraryPathTemplatePartDtoFixture.Create(
kind: nameof(LibraryPathPartKind.Artist),
representation: "{0}");
UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(pathTemplateParts: [literalPart, separatorPart, typedPart]);
// Act
List<Error> result = _validator.TestValidate(command);
// Assert
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError()
{
@@ -0,0 +1,169 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsQueryHandler"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsQueryHandlerTests
{
private readonly ILibraryPathPartCatalog _mockBookCatalog;
private readonly ILibraryPathPartCatalog _mockMusicCatalog;
private readonly GetLibraryPathTemplatePartsQueryHandler _sut;
private readonly GetLibraryPathTemplatePartsQueryFixture _getLibraryPathTemplatePartsQueryFixture = new();
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsQueryHandlerTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsQueryHandlerTests()
{
_mockBookCatalog = Substitute.For<ILibraryPathPartCatalog>();
_mockBookCatalog.SupportedLibraryType.Returns(LibraryType.Book);
_mockBookCatalog.GetPartDefinitions().Returns([]);
_mockBookCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty());
_mockMusicCatalog = Substitute.For<ILibraryPathPartCatalog>();
_mockMusicCatalog.SupportedLibraryType.Returns(LibraryType.Music);
_mockMusicCatalog.GetPartDefinitions().Returns([]);
_mockMusicCatalog.GetDefaultTemplate().Returns(LibraryPathTemplate.Empty());
_sut = new GetLibraryPathTemplatePartsQueryHandler([_mockBookCatalog, _mockMusicCatalog]);
}
[Theory]
[InlineData("")] // an absent library type
[InlineData(" ")] // a whitespace library type
[InlineData("NotARealLibraryType")] // an unknown library type
public async Task HandleAsync_WhenLibraryTypeIsUnknownOrAbsent_ShouldReturnUnknownLibraryTypeError(string libraryType)
{
// Arrange
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: libraryType);
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(DomainErrors.Library.UnknownLibraryType, result.FirstError);
_ = _mockBookCatalog.DidNotReceive().SupportedLibraryType;
_ = _mockMusicCatalog.DidNotReceive().SupportedLibraryType;
}
[Fact]
public async Task HandleAsync_WhenNoCatalogSupportsLibraryType_ShouldReturnEmptyPartsAndDefaultTemplateParts()
{
// Arrange
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Photo));
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Empty(result.Value.Parts);
Assert.Empty(result.Value.DefaultTemplateParts);
_ = _mockBookCatalog.Received(1).SupportedLibraryType;
_ = _mockMusicCatalog.Received(1).SupportedLibraryType;
_mockBookCatalog.DidNotReceive().GetPartDefinitions();
_mockBookCatalog.DidNotReceive().GetDefaultTemplate();
_mockMusicCatalog.DidNotReceive().GetPartDefinitions();
_mockMusicCatalog.DidNotReceive().GetDefaultTemplate();
}
[Fact]
public async Task HandleAsync_WhenCatalogSupportsLibraryType_ShouldMapPartDefinitionsAndDefaultTemplatePartsInOrder()
{
// Arrange
List<LibraryPathPartDefinition> partDefinitions =
[
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false),
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: true),
_libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "{0}",
isOptionalByDefault: false)
];
_mockMusicCatalog.GetPartDefinitions().Returns(partDefinitions);
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
LibraryPathPart separatorPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Separator,
representation: string.Empty,
isOptional: false);
LibraryPathPart trackNamePart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.TrackName,
representation: "{0}",
isOptional: true);
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create(parts: [artistPart, separatorPart, trackNamePart]);
_mockMusicCatalog.GetDefaultTemplate().Returns(defaultTemplate);
GetLibraryPathTemplatePartsQuery query = _getLibraryPathTemplatePartsQueryFixture.Create(libraryType: nameof(LibraryType.Music));
// Act
Result<LibraryPathTemplateCatalogResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(3, result.Value.Parts.Count);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.Parts[0].Kind);
Assert.Equal(LibraryPathValueType.Text.ToString(), result.Value.Parts[0].ValueType);
Assert.Equal("{0}", result.Value.Parts[0].DefaultRepresentation);
Assert.False(result.Value.Parts[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackNumber.ToString(), result.Value.Parts[1].Kind);
Assert.Equal(LibraryPathValueType.Integer.ToString(), result.Value.Parts[1].ValueType);
Assert.Equal("{0:00}", result.Value.Parts[1].DefaultRepresentation);
Assert.True(result.Value.Parts[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseYear.ToString(), result.Value.Parts[2].Kind);
Assert.Equal(LibraryPathValueType.Year.ToString(), result.Value.Parts[2].ValueType);
Assert.Equal("{0}", result.Value.Parts[2].DefaultRepresentation);
Assert.False(result.Value.Parts[2].IsOptionalByDefault);
Assert.Equal(3, result.Value.DefaultTemplateParts.Count);
Assert.Equal(LibraryPathPartKind.Artist.ToString(), result.Value.DefaultTemplateParts[0].Kind);
Assert.Equal("{0}", result.Value.DefaultTemplateParts[0].Representation);
Assert.False(result.Value.DefaultTemplateParts[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator.ToString(), result.Value.DefaultTemplateParts[1].Kind);
Assert.Equal(string.Empty, result.Value.DefaultTemplateParts[1].Representation);
Assert.False(result.Value.DefaultTemplateParts[1].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackName.ToString(), result.Value.DefaultTemplateParts[2].Kind);
Assert.Equal("{0}", result.Value.DefaultTemplateParts[2].Representation);
Assert.True(result.Value.DefaultTemplateParts[2].IsOptional);
_mockMusicCatalog.Received(1).GetPartDefinitions();
_mockMusicCatalog.Received(1).GetDefaultTemplate();
_mockBookCatalog.DidNotReceive().GetPartDefinitions();
_mockBookCatalog.DidNotReceive().GetDefaultTemplate();
}
}
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Collections.Generic;
@@ -28,6 +29,11 @@ public class LibraryConfigurationTests
_context = new LuminaDbContext(new DbContextOptionsBuilder<LuminaDbContext>().UseSqlite("Data Source=:memory:").Options);
}
/// <summary>
/// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits.
/// </summary>
private IModel DesignTimeModel => _context.GetService<IDesignTimeModel>().Model;
[Fact]
public void Configure_WhenApplied_ShouldSetTableNameAndKey()
{
@@ -64,6 +70,22 @@ public class LibraryConfigurationTests
Assert.Equal(true, downloadMetadataProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigurePathTemplateFingerprint()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty fingerprintProperty = entityType.GetProperty(nameof(LibraryEntity.PathTemplateFingerprint));
// Assert
Assert.True(fingerprintProperty.IsNullable);
Assert.Equal(typeof(string), fingerprintProperty.ClrType);
Assert.Equal(64, fingerprintProperty.GetMaxLength());
Assert.Equal(11, fingerprintProperty.GetColumnOrder());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations()
{
@@ -71,15 +93,78 @@ public class LibraryConfigurationTests
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
List<IEntityType> ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)];
IEntityType contentLocationType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryContentLocationEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
// Assert
IEntityType contentLocationType = Assert.Single(ownedTypes);
Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType);
Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName());
Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplateParts()
{
// Arrange
IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!;
// Act
IEntityType partEntityType = Assert.Single(
_context.Model.GetEntityTypes(),
ownedType => ownedType.IsOwned()
&& ownedType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name);
IForeignKey ownershipForeignKey = partEntityType.FindOwnership()!;
// Assert
Assert.Equal("LibraryPathTemplateParts", partEntityType.GetTableName());
Assert.Equal(["Id"], partEntityType.FindPrimaryKey()!.Properties.Select(property => property.Name));
Assert.Equal(typeof(LibraryEntity), ownershipForeignKey.PrincipalEntityType.ClrType);
Assert.Equal(["LibraryId"], ownershipForeignKey.Properties.Select(property => property.Name));
Assert.True(ownershipForeignKey.IsRequired);
IIndex uniqueIndex = Assert.Single(
partEntityType.GetIndexes(),
index => index.Properties.Select(property => property.Name).SequenceEqual(["LibraryId", nameof(LibraryPathTemplatePartEntity.Position)]));
Assert.True(uniqueIndex.IsUnique);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureOwnedPathTemplatePartColumns()
{
// Arrange
IEntityType partEntityType = DesignTimeModel.GetEntityTypes()
.Single(entityType => entityType.IsOwned()
&& entityType.ClrType == typeof(LibraryPathTemplatePartEntity)
&& entityType.GetTableName() == "LibraryPathTemplateParts");
// Act
IProperty positionProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Position));
IProperty kindProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Kind));
IProperty representationProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.Representation));
IProperty isOptionalProperty = partEntityType.GetProperty(nameof(LibraryPathTemplatePartEntity.IsOptional));
// Assert
Assert.Equal("Position", positionProperty.GetColumnName());
Assert.False(positionProperty.IsNullable);
Assert.Equal(typeof(LibraryPathPartKind), kindProperty.ClrType);
Assert.Equal(typeof(string), kindProperty.GetTypeMapping().Converter!.ProviderClrType);
Assert.Equal("TEXT", kindProperty.GetColumnType());
Assert.Equal(32, kindProperty.GetMaxLength());
Assert.False(kindProperty.IsNullable);
Assert.Equal(512, representationProperty.GetMaxLength());
Assert.False(representationProperty.IsNullable);
Assert.Equal(typeof(bool), isOptionalProperty.ClrType);
Assert.False(isOptionalProperty.IsNullable);
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureRelationships()
{
@@ -111,4 +196,23 @@ public class LibraryConfigurationTests
Assert.False(createdOnUtcProperty.IsNullable);
Assert.Null(updatedOnUtcProperty.GetDefaultValue());
}
[Fact]
public void Configure_WhenApplied_ShouldConfigureAuditColumnOrders()
{
// Arrange
IEntityType entityType = DesignTimeModel.FindEntityType(typeof(LibraryEntity))!;
// Act
IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc));
IProperty createdByProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedBy));
IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc));
IProperty updatedByProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedBy));
// Assert
Assert.Equal(12, createdOnUtcProperty.GetColumnOrder());
Assert.Equal(13, createdByProperty.GetColumnOrder());
Assert.Equal(14, updatedOnUtcProperty.GetColumnOrder());
Assert.Equal(15, updatedByProperty.GetColumnOrder());
}
}
@@ -8,6 +8,7 @@ using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
@@ -29,6 +30,7 @@ public class LibraryRepositoryTests
private readonly LuminaDbContext _mockContext;
private readonly LibraryRepository _sut;
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryPathTemplatePartEntityFixture _libraryPathTemplatePartEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryRepositoryTests"/> class.
@@ -230,4 +232,307 @@ public class LibraryRepositoryTests
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
}
[Fact]
public async Task InsertAsync_WhenLibraryHasPathTemplateParts_ShouldAddLibraryAndItsPartsToContext()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Separator, representation: "/", isOptional: false);
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity library = _libraryEntityFixture.Create(
contentLocations: [],
pathTemplateParts: [firstPart, secondPart, thirdPart],
pathTemplateFingerprint: "path-template-fingerprint");
// Act
Result<Created> result = await _sut.InsertAsync(library, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Created, result.Value);
EntityEntry<LibraryEntity>? addedLibrary = _mockContext.ChangeTracker.Entries<LibraryEntity>()
.FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id);
Assert.NotNull(addedLibrary);
Assert.Equal("path-template-fingerprint", addedLibrary!.Entity.PathTemplateFingerprint);
List<EntityEntry<LibraryPathTemplatePartEntity>> partEntries = [.. _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.Where(entityEntry => entityEntry.State == EntityState.Added)];
Assert.Equal(3, partEntries.Count);
Assert.Equal([0, 1, 2], partEntries.Select(entityEntry => entityEntry.Entity.Position).OrderBy(position => position));
LibraryPathTemplatePartEntity storedFirstPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 0).Entity;
Assert.Equal(LibraryPathPartKind.Artist, storedFirstPart.Kind);
Assert.Equal("{0}", storedFirstPart.Representation);
Assert.False(storedFirstPart.IsOptional);
LibraryPathTemplatePartEntity storedSecondPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 1).Entity;
Assert.Equal(LibraryPathPartKind.Separator, storedSecondPart.Kind);
Assert.Equal("/", storedSecondPart.Representation);
Assert.False(storedSecondPart.IsOptional);
LibraryPathTemplatePartEntity storedThirdPart = partEntries.Single(entityEntry => entityEntry.Entity.Position == 2).Entity;
Assert.Equal(LibraryPathPartKind.Series, storedThirdPart.Kind);
Assert.Equal("{0}", storedThirdPart.Representation);
Assert.True(storedThirdPart.IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartRepresentationChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{1}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
EntityEntry<LibraryPathTemplatePartEntity>? keptEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, keptPart));
Assert.NotNull(keptEntry);
Assert.Equal(EntityState.Unchanged, keptEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
Assert.False(retrievedResult.IsFailure);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal("{0}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0).Representation);
Assert.Equal("{1}", retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Representation);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartKindChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(LibraryPathPartKind.Series, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).Kind);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartIsOptionalChanges_ShouldReplaceThatPart()
{
// Arrange
LibraryPathTemplatePartEntity keptPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity replacedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [keptPart, replacedPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity replacementPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [keptPart, replacementPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? replacedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, replacedPart));
Assert.NotNull(replacedEntry);
Assert.Equal(EntityState.Deleted, replacedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.True(retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1).IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartPositionIsRemoved_ShouldRemoveThatPart()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity removedPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity thirdPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, removedPart, thirdPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [firstPart, thirdPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? removedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, removedPart));
Assert.NotNull(removedEntry);
Assert.Equal(EntityState.Deleted, removedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal([0, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartPositionIsAdded_ShouldAddThatPart()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity addedPart = _libraryPathTemplatePartEntityFixture.Create(position: 2, kind: LibraryPathPartKind.Series, representation: "{0}", isOptional: true);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [firstPart, secondPart, addedPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
EntityEntry<LibraryPathTemplatePartEntity>? addedEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, addedPart));
Assert.NotNull(addedEntry);
Assert.Equal(EntityState.Added, addedEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(3, retrievedLibrary.PathTemplateParts.Count);
Assert.Equal([0, 1, 2], retrievedLibrary.PathTemplateParts.Select(part => part.Position).OrderBy(position => position));
LibraryPathTemplatePartEntity storedAddedPart = retrievedLibrary.PathTemplateParts.Single(part => part.Position == 2);
Assert.Equal(LibraryPathPartKind.Series, storedAddedPart.Kind);
Assert.Equal("{0}", storedAddedPart.Representation);
Assert.True(storedAddedPart.IsOptional);
}
[Fact]
public async Task UpdateAsync_WhenPathTemplatePartsAreUnchanged_ShouldKeepExistingParts()
{
// Arrange
LibraryPathTemplatePartEntity firstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity secondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [firstPart, secondPart]);
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryPathTemplatePartEntity equivalentFirstPart = _libraryPathTemplatePartEntityFixture.Create(position: 0, kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
LibraryPathTemplatePartEntity equivalentSecondPart = _libraryPathTemplatePartEntityFixture.Create(position: 1, kind: LibraryPathPartKind.Title, representation: "{0}", isOptional: false);
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [equivalentFirstPart, equivalentSecondPart]);
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
Assert.DoesNotContain(
_mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>(),
entityEntry => entityEntry.State == EntityState.Added || entityEntry.State == EntityState.Deleted);
EntityEntry<LibraryPathTemplatePartEntity>? firstEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, firstPart));
Assert.NotNull(firstEntry);
Assert.Equal(EntityState.Unchanged, firstEntry!.State);
EntityEntry<LibraryPathTemplatePartEntity>? secondEntry = _mockContext.ChangeTracker.Entries<LibraryPathTemplatePartEntity>()
.SingleOrDefault(entityEntry => ReferenceEquals(entityEntry.Entity, secondPart));
Assert.NotNull(secondEntry);
Assert.Equal(EntityState.Unchanged, secondEntry!.State);
Result<LibraryEntity?> retrievedResult = await _sut.GetByIdAsync(library.Id, cancellationToken: CancellationToken.None);
LibraryEntity retrievedLibrary = Assert.IsType<LibraryEntity>(retrievedResult.Value);
Assert.Equal(2, retrievedLibrary.PathTemplateParts.Count);
Assert.Same(firstPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 0));
Assert.Same(secondPart, retrievedLibrary.PathTemplateParts.Single(part => part.Position == 1));
}
[Fact]
public async Task UpdateAsync_WhenPathTemplateFingerprintChanges_ShouldUpdateIt()
{
// Arrange
LibraryEntity library = _libraryEntityFixture.Create(contentLocations: [], pathTemplateParts: [], pathTemplateFingerprint: "old-fingerprint");
_mockContext.Libraries.Add(library);
await _mockContext.SaveChangesAsync();
LibraryEntity updatedLibrary = _libraryEntityFixture.Create(
id: library.Id,
userId: library.UserId,
contentLocations: [],
pathTemplateParts: [],
pathTemplateFingerprint: "new-fingerprint");
// Act
Result<Updated> result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(Result.Updated, result.Value);
LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id);
Assert.NotNull(retrievedLibrary);
Assert.Equal("new-fingerprint", retrievedLibrary!.PathTemplateFingerprint);
}
}
@@ -42,7 +42,7 @@ public class ErrorsTests
{
// Assert
// The count assertion fails when an error is added or removed, reminding to update the assertions below.
Assert.Equal(14, typeof(DomainErrors.Library).GetProperties().Length);
Assert.Equal(18, typeof(DomainErrors.Library).GetProperties().Length);
AssertError(DomainErrors.Library.CannotScanLockedLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.CannotScanDisabledLibrary, ErrorType.Forbidden);
AssertError(DomainErrors.Library.LibraryIdCannotBeEmpty, ErrorType.Validation);
@@ -52,11 +52,15 @@ public class ErrorsTests
AssertError(DomainErrors.Library.LibraryNotFound, ErrorType.NotFound);
AssertError(DomainErrors.Library.LibraryTypeCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.CoverFileMustBeAnImage, ErrorType.Validation);
AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Unexpected);
AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Forbidden);
AssertError(DomainErrors.Library.PathsListCannotBeNull, ErrorType.Validation);
AssertError(DomainErrors.Library.PathsListCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.TitleMustBeMaximum255CharactersLong, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateLiteralCannotBeEmpty, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateValuePartMustContainSinglePlaceholder, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplatePartKindNotSupportedForLibraryType, ErrorType.Validation);
AssertError(DomainErrors.Library.PathTemplateIsNotSupportedForLibraryType, ErrorType.Validation);
}
[Fact]
@@ -0,0 +1,163 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryPathPartCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathPartCatalogTests
{
private readonly MusicLibraryPathPartCatalog _sut = new();
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnMusic()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Music, result);
}
[Fact]
public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions()
{
// Act
IReadOnlyList<LibraryPathPartDefinition> result = _sut.GetPartDefinitions();
// Assert
Assert.Equal(10, result.Count);
Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind);
Assert.Equal(LibraryPathValueType.None, result[0].ValueType);
Assert.Equal(string.Empty, result[0].DefaultRepresentation);
Assert.False(result[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(LibraryPathValueType.None, result[1].ValueType);
Assert.Equal(string.Empty, result[1].DefaultRepresentation);
Assert.False(result[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Artist, result[2].Kind);
Assert.Equal(LibraryPathValueType.Text, result[2].ValueType);
Assert.Equal("{0}", result[2].DefaultRepresentation);
Assert.False(result[2].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseType, result[3].Kind);
Assert.Equal(LibraryPathValueType.Enum, result[3].ValueType);
Assert.Equal("{0}", result[3].DefaultRepresentation);
Assert.False(result[3].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
Assert.Equal(LibraryPathValueType.Year, result[4].ValueType);
Assert.Equal("{0}", result[4].DefaultRepresentation);
Assert.False(result[4].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.ReleaseName, result[5].Kind);
Assert.Equal(LibraryPathValueType.Text, result[5].ValueType);
Assert.Equal("{0}", result[5].DefaultRepresentation);
Assert.False(result[5].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackNumber, result[6].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType);
Assert.Equal("{0:00}", result[6].DefaultRepresentation);
Assert.False(result[6].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.TrackName, result[7].Kind);
Assert.Equal(LibraryPathValueType.Text, result[7].ValueType);
Assert.Equal("{0}", result[7].DefaultRepresentation);
Assert.False(result[7].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Extension, result[8].Kind);
Assert.Equal(LibraryPathValueType.Text, result[8].ValueType);
Assert.Equal("{0}", result[8].DefaultRepresentation);
Assert.False(result[8].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[9].ValueType);
Assert.Equal("{0:00}", result[9].DefaultRepresentation);
Assert.True(result[9].IsOptionalByDefault);
}
[Fact]
public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts()
{
// Act
IReadOnlyList<LibraryPathPart> result = _sut.GetDefaultTemplate().Parts;
// Assert
Assert.Equal(16, result.Count);
Assert.Equal(LibraryPathPartKind.Artist, result[0].Kind);
Assert.Equal("{0}", result[0].Representation);
Assert.False(result[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(string.Empty, result[1].Representation);
Assert.False(result[1].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseType, result[2].Kind);
Assert.Equal("{0}", result[2].Representation);
Assert.False(result[2].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[3].Kind);
Assert.Equal(string.Empty, result[3].Representation);
Assert.False(result[3].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseYear, result[4].Kind);
Assert.Equal("{0}", result[4].Representation);
Assert.False(result[4].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind);
Assert.Equal(" - ", result[5].Representation);
Assert.False(result[5].IsOptional);
Assert.Equal(LibraryPathPartKind.ReleaseName, result[6].Kind);
Assert.Equal("{0}", result[6].Representation);
Assert.False(result[6].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[7].Kind);
Assert.Equal(string.Empty, result[7].Representation);
Assert.True(result[7].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind);
Assert.Equal("Disk ", result[8].Representation);
Assert.True(result[8].IsOptional);
Assert.Equal(LibraryPathPartKind.DiscNumber, result[9].Kind);
Assert.Equal("{0:00}", result[9].Representation);
Assert.True(result[9].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[10].Kind);
Assert.Equal(string.Empty, result[10].Representation);
Assert.False(result[10].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackNumber, result[11].Kind);
Assert.Equal("{0:00}", result[11].Representation);
Assert.False(result[11].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[12].Kind);
Assert.Equal(" - ", result[12].Representation);
Assert.False(result[12].IsOptional);
Assert.Equal(LibraryPathPartKind.TrackName, result[13].Kind);
Assert.Equal("{0}", result[13].Representation);
Assert.False(result[13].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[14].Kind);
Assert.Equal(".", result[14].Representation);
Assert.False(result[14].IsOptional);
Assert.Equal(LibraryPathPartKind.Extension, result[15].Kind);
Assert.Equal("{0}", result[15].Representation);
Assert.False(result[15].IsOptional);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="MusicLibraryPathMetadata"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicLibraryPathMetadataTests
{
private readonly MusicLibraryPathMetadataFixture _musicLibraryPathMetadataFixture = new();
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
[Fact]
public void FromParsedLibraryPath_WhenAllValuesAreCaptured_ShouldMapAllFields()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen",
[LibraryPathPartKind.ReleaseType] = "Album",
[LibraryPathPartKind.ReleaseYear] = "1975",
[LibraryPathPartKind.ReleaseName] = "A Night at the Opera",
[LibraryPathPartKind.TrackNumber] = "11",
[LibraryPathPartKind.DiscNumber] = "1",
[LibraryPathPartKind.TrackName] = "Bohemian Rhapsody"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.Equal("Queen", result.ArtistName.Value);
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
Assert.Equal(1975, result.ReleaseYear.Value);
Assert.Equal("A Night at the Opera", result.ReleaseName.Value);
Assert.Equal(11, result.TrackNumber.Value);
Assert.Equal(1, result.DiscNumber.Value);
Assert.Equal("Bohemian Rhapsody", result.TrackTitle.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsRecognized_ShouldParseItCaseInsensitively()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseType] = "album"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.True(result.ReleaseType.HasValue);
Assert.Equal(MusicReleaseType.Album, result.ReleaseType.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsNotRecognized_ShouldFallBackToOther()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseType] = "not a release type"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.True(result.ReleaseType.HasValue);
Assert.Equal(MusicReleaseType.Other, result.ReleaseType.Value);
}
[Fact]
public void FromParsedLibraryPath_WhenReleaseTypeIsAbsent_ShouldLeaveItUnset()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen"
});
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.False(result.ReleaseType.HasValue);
}
[Fact]
public void FromParsedLibraryPath_WhenValuesAreAbsent_ShouldLeaveThemUnset()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(includeValues: false);
// Act
MusicLibraryPathMetadata result = MusicLibraryPathMetadata.FromParsedLibraryPath(parsedPath);
// Assert
Assert.False(result.ArtistName.HasValue);
Assert.False(result.ReleaseType.HasValue);
Assert.False(result.ReleaseYear.HasValue);
Assert.False(result.ReleaseName.HasValue);
Assert.False(result.TrackNumber.HasValue);
Assert.False(result.DiscNumber.HasValue);
Assert.False(result.TrackTitle.HasValue);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create();
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(
artistName: firstMetadata.ArtistName.Value,
releaseType: firstMetadata.ReleaseType.Value,
releaseYear: firstMetadata.ReleaseYear.Value,
releaseName: firstMetadata.ReleaseName.Value,
trackNumber: firstMetadata.TrackNumber.Value,
discNumber: firstMetadata.DiscNumber.Value,
trackTitle: firstMetadata.TrackTitle.Value);
// Assert
Assert.Equal(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentArtistName_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Queen");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(artistName: "Pink Floyd");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseType_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Album);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseType: MusicReleaseType.Single);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseYear_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1975);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseYear: 1980);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentReleaseName_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "A Night at the Opera");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(releaseName: "The Game");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentTrackNumber_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 11);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackNumber: 12);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentDiscNumber_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 1);
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(discNumber: 2);
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
[Fact]
public void Equals_WithDifferentTrackTitle_ShouldReturnFalse()
{
// Arrange
MusicLibraryPathMetadata firstMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Bohemian Rhapsody");
// Act
MusicLibraryPathMetadata secondMetadata = _musicLibraryPathMetadataFixture.Create(trackTitle: "Love of My Life");
// Assert
Assert.NotEqual(firstMetadata, secondMetadata);
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPart"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartTests
{
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
[Fact]
public void Create_WhenKindIsSeparator_ShouldCreateSeparatorWithoutRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Separator, "/", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Separator, result.Value.Kind);
Assert.Equal(string.Empty, result.Value.Representation);
}
[Fact]
public void Create_WhenKindIsLiteralWithText_ShouldCreateLiteralWithThatRepresentation()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, " - ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(LibraryPathPartKind.Literal, result.Value.Kind);
Assert.Equal(" - ", result.Value.Representation);
}
[Theory]
[InlineData(null)] // the representation is absent
[InlineData("")] // the representation is empty
[InlineData(" ")] // the representation is whitespace
public void Create_WhenKindIsNotSeparatorAndRepresentationIsEmpty_ShouldReturnLiteralCannotBeEmptyError(string? representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateLiteralCannotBeEmpty, result.FirstError);
}
[Fact]
public void Create_WhenTypedPartContainsSinglePlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, "{0}", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("{0}", result.Value.Representation);
}
[Fact]
public void Create_WhenTypedPartContainsFixedWidthPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.TrackNumber, "Disc {0:00}", isOptional: true);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disc {0:00}", result.Value.Representation);
Assert.True(result.Value.IsOptional);
}
[Theory]
[InlineData("no placeholder")] // the mask carries no value placeholder
[InlineData("{0} {0}")] // the mask carries more than one value placeholder
public void Create_WhenTypedPartDoesNotContainExactlyOnePlaceholder_ShouldReturnError(string representation)
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Artist, representation, isOptional: false);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Lumina.Domain.Common.Errors.Errors.Library.PathTemplateValuePartMustContainSinglePlaceholder, result.FirstError);
}
[Fact]
public void Create_WhenLiteralContainsNoPlaceholder_ShouldCreateThePart()
{
// Act
Result<LibraryPathPart> result = LibraryPathPart.Create(LibraryPathPartKind.Literal, "Disk ", isOptional: false);
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Disk ", result.Value.Representation);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: true);
// Assert
Assert.Equal(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "Artist: {0}", isOptional: false);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
[Fact]
public void Equals_WithDifferentIsOptional_ShouldReturnFalse()
{
// Arrange
LibraryPathPart firstPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: false);
// Act
LibraryPathPart secondPart = _libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true);
// Assert
Assert.NotEqual(firstPart, secondPart);
}
}
@@ -0,0 +1,94 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplate"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateTests
{
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
[Fact]
public void Create_WhenCalledWithParts_ShouldCreateTemplateWithThoseParts()
{
// Arrange
LibraryPathTemplate template = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate result = LibraryPathTemplate.Create(template.Parts);
// Assert
Assert.Equal(template.Parts, result.Parts);
Assert.False(result.IsEmpty);
}
[Fact]
public void Empty_WhenCalled_ShouldCreateTemplateWithoutParts()
{
// Act
LibraryPathTemplate result = LibraryPathTemplate.Empty();
// Assert
Assert.Empty(result.Parts);
Assert.True(result.IsEmpty);
}
[Fact]
public void Create_WhenSourceCollectionIsLaterModified_ShouldNotAffectTheTemplate()
{
// Arrange
List<LibraryPathPart> sourceParts = [.. _libraryPathTemplateFixture.Create().Parts];
int originalCount = sourceParts.Count;
// Act
LibraryPathTemplate template = LibraryPathTemplate.Create(sourceParts);
sourceParts.Clear();
// Assert
Assert.Equal(originalCount, template.Parts.Count);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Create(firstTemplate.Parts);
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WithDifferentParts_ShouldReturnFalse()
{
// Arrange
LibraryPathTemplate firstTemplate = _libraryPathTemplateFixture.Create();
// Act
LibraryPathTemplate secondTemplate = _libraryPathTemplateFixture.Create();
// Assert
Assert.NotEqual(firstTemplate, secondTemplate);
}
[Fact]
public void Equals_WhenBothTemplatesAreEmpty_ShouldReturnTrue()
{
// Act
LibraryPathTemplate firstTemplate = LibraryPathTemplate.Empty();
LibraryPathTemplate secondTemplate = LibraryPathTemplate.Empty();
// Assert
Assert.Equal(firstTemplate, secondTemplate);
}
}
@@ -0,0 +1,497 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using NSubstitute;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathTemplateService"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathTemplateServiceTests
{
private readonly ILibraryPathPartCatalog _mockCatalog = Substitute.For<ILibraryPathPartCatalog>();
private readonly LibraryPathTemplateService _sut;
private readonly LibraryPathPartFixture _libraryPathPartFixture = new();
private readonly LibraryPathTemplateFixture _libraryPathTemplateFixture = new();
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="LibraryPathTemplateServiceTests"/> class.
/// </summary>
public LibraryPathTemplateServiceTests()
{
_mockCatalog.SupportedLibraryType.Returns(LibraryType.Music);
_sut = new LibraryPathTemplateService([_mockCatalog]);
}
[Fact]
public void GetDefaultTemplate_WhenCatalogExists_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
LibraryPathTemplate defaultTemplate = _libraryPathTemplateFixture.Create();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Music);
// Assert
Assert.Equal(defaultTemplate, result);
}
[Fact]
public void GetDefaultTemplate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnAnEmptyTemplate()
{
// Act
LibraryPathTemplate result = _sut.GetDefaultTemplate(LibraryType.Book);
// Assert
Assert.True(result.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmpty_ShouldReturnTheCatalogDefaultTemplate()
{
// Arrange
SetupCatalog();
LibraryPathTemplate defaultTemplate = CreateMusicTemplate();
_mockCatalog.GetDefaultTemplate().Returns(defaultTemplate);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, []);
// Assert
Assert.False(result.IsFailure);
Assert.Equal(defaultTemplate, result.Value);
_mockCatalog.Received(1).GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreEmptyAndNoCatalogExists_ShouldReturnAnEmptyTemplate()
{
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, []);
// Assert
Assert.False(result.IsFailure);
Assert.True(result.Value.IsEmpty);
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotEmpty_ShouldReturnATemplateWithThoseParts()
{
// Arrange
SetupCatalog();
LibraryPathPart providedPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [providedPart]);
// Assert
Assert.False(result.IsFailure);
LibraryPathPart pathPart = Assert.Single(result.Value.Parts);
Assert.Equal(LibraryPathPartKind.Artist, pathPart.Kind);
Assert.Equal("{0}", pathPart.Representation);
Assert.False(pathPart.IsOptional);
_mockCatalog.DidNotReceive().GetDefaultTemplate();
}
[Fact]
public void ResolveTemplate_WhenProvidedPartsAreNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathPart releaseNamePart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Music, [releaseNamePart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void ResolveTemplate_WhenNoCatalogExistsForTheLibraryTypeAndPartsAreProvided_ShouldReturnNotSupportedError()
{
// Arrange
LibraryPathPart artistPart = _libraryPathPartFixture.Create(
kind: LibraryPathPartKind.Artist,
representation: "{0}",
isOptional: false);
// Act
Result<LibraryPathTemplate> result = _sut.ResolveTemplate(LibraryType.Book, [artistPart]);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenTemplateIsEmpty_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenTemplateIsEmptyAndNoCatalogExists_ShouldReturnSuccess()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, LibraryPathTemplate.Empty());
// Assert
Assert.False(result.IsFailure);
}
[Fact]
public void Validate_WhenNoCatalogExistsForTheLibraryType_ShouldReturnNotSupportedError()
{
// Act
Result<Success> result = _sut.Validate(LibraryType.Book, CreateMusicTemplate());
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenPartKindIsNotSupportedByTheCatalog_ShouldReturnError()
{
// Arrange
SetupCatalog(definitions:
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseName, representation: "{0}")
]);
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplatePartKindNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Validate_WhenAllPartKindsAreSupportedByTheCatalog_ShouldReturnSuccess()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<Success> result = _sut.Validate(LibraryType.Music, template);
// Assert
Assert.False(result.IsFailure);
}
[Theory]
[InlineData("")] // the relative path is empty
[InlineData(" ")] // the relative path is whitespace
public void Parse_WhenRelativePathIsEmpty_ShouldReturnNull(string relativePath)
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, CreateMusicTemplate(), relativePath, '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenTemplateIsEmpty_ShouldReturnNull()
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, LibraryPathTemplate.Empty(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenTemplateIsNotSupportedForTheLibraryType_ShouldReturnError()
{
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Book, CreateMusicTemplate(), "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Library.PathTemplateIsNotSupportedForLibraryType, result.FirstError);
}
[Fact]
public void Parse_WhenPathMatchesTheTemplate_ShouldReturnTheCapturedValues()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/1973 - Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
ParsedLibraryPath parsedPath = result.Value!;
Assert.Equal("Pink Floyd", parsedPath.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(1973, parsedPath.GetInt(LibraryPathPartKind.ReleaseYear).Value);
Assert.Equal("Time", parsedPath.GetString(LibraryPathPartKind.TrackName).Value);
Assert.Equal("mp3", parsedPath.GetString(LibraryPathPartKind.Extension).Value);
}
[Fact]
public void Parse_WhenPathDoesNotMatchTheTemplate_ShouldReturnNull()
{
// Arrange
SetupCatalog();
LibraryPathTemplate template = CreateMusicTemplate();
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/no year/Time.mp3", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenIntegerPartHasAFixedWidth_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/07", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(7, result.Value!.GetInt(LibraryPathPartKind.TrackNumber).Value);
}
[Fact]
public void Parse_WhenIntegerPartDoesNotMatchTheFixedWidth_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackNumber, representation: "{0:00}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/007", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenYearPartHasAFourDigitValue_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "1973", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal(1973, result.Value!.GetInt(LibraryPathPartKind.ReleaseYear).Value);
}
[Fact]
public void Parse_WhenYearPartDoesNotHaveAFourDigitValue_ShouldReturnNull()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "73", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Null(result.Value);
}
[Fact]
public void Parse_WhenAnOptionalRunIsAbsent_ShouldStillMatchThePath()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
Assert.False(result.Value.GetInt(LibraryPathPartKind.DiscNumber).HasValue);
}
[Fact]
public void Parse_WhenAnOptionalRunIsPresent_ShouldCaptureIt()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.DiscNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}")
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.DiscNumber, representation: "{0:00}", isOptional: true)
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Pink Floyd/02", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Pink Floyd", result.Value!.GetString(LibraryPathPartKind.Artist).Value);
Assert.Equal(2, result.Value.GetInt(LibraryPathPartKind.DiscNumber).Value);
}
[Fact]
public void Parse_WhenTheSameKindAppearsMoreThanOnce_ShouldKeepTheFirstCapture()
{
// Arrange
SetupCatalog(
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Author, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Title, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty)
]);
LibraryPathTemplate template = _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Title, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Author, representation: "{0}")
]);
// Act
Result<ParsedLibraryPath?> result = _sut.Parse(LibraryType.Music, template, "Tolkien/The Lord of the Rings - J.R.R. Tolkien", '/');
// Assert
Assert.False(result.IsFailure);
Assert.Equal("Tolkien", result.Value!.GetString(LibraryPathPartKind.Author).Value);
}
/// <summary>
/// Sets up the mock catalog to return a music-like set of part definitions and a default template.
/// </summary>
/// <param name="definitions">Optional. The part definitions the catalog returns. When omitted, a standard music set is used.</param>
private void SetupCatalog(IReadOnlyList<LibraryPathPartDefinition>? definitions = null)
{
_mockCatalog.GetPartDefinitions().Returns(definitions ??
[
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Literal, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Artist, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Separator, valueType: LibraryPathValueType.None, defaultRepresentation: string.Empty),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.ReleaseYear, valueType: LibraryPathValueType.Year, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackNumber, valueType: LibraryPathValueType.Integer, defaultRepresentation: "{0:00}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.TrackName, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}"),
_libraryPathPartDefinitionFixture.Create(kind: LibraryPathPartKind.Extension, valueType: LibraryPathValueType.Text, defaultRepresentation: "{0}")
]);
}
/// <summary>
/// Creates a music-like path template whose parts are all supported by the standard music set of definitions.
/// </summary>
/// <returns>The created path template.</returns>
private LibraryPathTemplate CreateMusicTemplate()
{
return _libraryPathTemplateFixture.Create(
[
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Artist, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Separator, representation: string.Empty),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.ReleaseYear, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: " - "),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.TrackName, representation: "{0}"),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Literal, representation: "."),
_libraryPathPartFixture.Create(kind: LibraryPathPartKind.Extension, representation: "{0}")
]);
}
}
@@ -0,0 +1,129 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="LibraryPathPartDefinition"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryPathPartDefinitionTests
{
private readonly LibraryPathPartDefinitionFixture _libraryPathPartDefinitionFixture = new();
[Fact]
public void Constructor_WhenCalled_ShouldSetAllProperties()
{
// Act
LibraryPathPartDefinition definition = new(LibraryPathPartKind.TrackNumber, LibraryPathValueType.Integer, "{0:00}", isOptionalByDefault: true);
// Assert
Assert.Equal(LibraryPathPartKind.TrackNumber, definition.Kind);
Assert.Equal(LibraryPathValueType.Integer, definition.ValueType);
Assert.Equal("{0:00}", definition.DefaultRepresentation);
Assert.True(definition.IsOptionalByDefault);
}
[Fact]
public void Equals_WithSameValues_ShouldReturnTrue()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}",
isOptionalByDefault: false);
// Assert
Assert.Equal(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentKind_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.Artist,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseName,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentValueType_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.TrackNumber,
valueType: LibraryPathValueType.Text,
defaultRepresentation: "{0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentDefaultRepresentation_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "{0}");
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.ReleaseYear,
valueType: LibraryPathValueType.Year,
defaultRepresentation: "Year {0}");
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
[Fact]
public void Equals_WithDifferentIsOptionalByDefault_ShouldReturnFalse()
{
// Arrange
LibraryPathPartDefinition firstDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: false);
// Act
LibraryPathPartDefinition secondDefinition = _libraryPathPartDefinitionFixture.Create(
kind: LibraryPathPartKind.DiscNumber,
valueType: LibraryPathValueType.Integer,
defaultRepresentation: "{0:00}",
isOptionalByDefault: true);
// Assert
Assert.NotEqual(firstDefinition, secondDefinition);
}
}
@@ -0,0 +1,230 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
/// <summary>
/// Contains unit tests for the <see cref="ParsedLibraryPath"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ParsedLibraryPathTests
{
private readonly ParsedLibraryPathFixture _parsedLibraryPathFixture = new();
[Fact]
public void Create_WhenCalledWithValues_ShouldExposeThoseValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
// Act
ParsedLibraryPath result = ParsedLibraryPath.Create(values);
// Assert
Assert.Equal(2, result.Values.Count);
Assert.Equal("Pink Floyd", result.Values[LibraryPathPartKind.Artist]);
Assert.Equal("Time", result.Values[LibraryPathPartKind.TrackName]);
}
[Fact]
public void GetString_WhenKindIsCaptured_ShouldReturnTheTrimmedValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " Pink Floyd "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.True(result.HasValue);
Assert.Equal("Pink Floyd", result.Value);
}
[Fact]
public void GetString_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.TrackName);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetString_WhenCapturedValueIsWhitespace_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = " "
});
// Act
Optional<string> result = parsedPath.GetString(LibraryPathPartKind.Artist);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenKindIsCapturedWithAnInteger_ShouldReturnTheValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "1973"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.True(result.HasValue);
Assert.Equal(1973, result.Value);
}
[Fact]
public void GetInt_WhenKindIsNotCaptured_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void GetInt_WhenCapturedValueIsNotAnInteger_ShouldReturnNoValue()
{
// Arrange
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.ReleaseYear] = "not a year"
});
// Act
Optional<int> result = parsedPath.GetInt(LibraryPathPartKind.ReleaseYear);
// Assert
Assert.False(result.HasValue);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnAllCapturedValues()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.Equal(values, result);
}
[Fact]
public void ToDictionary_WhenCalled_ShouldReturnACopy()
{
// Arrange
Dictionary<LibraryPathPartKind, string> values = new()
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
};
ParsedLibraryPath parsedPath = _parsedLibraryPathFixture.Create(values);
// Act
IReadOnlyDictionary<LibraryPathPartKind, string> result = parsedPath.ToDictionary();
// Assert
Assert.NotSame(values, result);
}
[Fact]
public void Equals_WithSameValuesInDifferentOrder_ShouldReturnTrue()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd",
[LibraryPathPartKind.TrackName] = "Time"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.TrackName] = "Time",
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Assert
Assert.Equal(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentValues_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Queen"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
[Fact]
public void Equals_WithDifferentKeys_ShouldReturnFalse()
{
// Arrange
ParsedLibraryPath firstPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Artist] = "Pink Floyd"
});
// Act
ParsedLibraryPath secondPath = _parsedLibraryPathFixture.Create(new Dictionary<LibraryPathPartKind, string>
{
[LibraryPathPartKind.Title] = "Pink Floyd"
});
// Assert
Assert.NotEqual(firstPath, secondPath);
}
}
@@ -0,0 +1,137 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.PathTemplate;
/// <summary>
/// Contains unit tests for the <see cref="BookLibraryPathPartCatalog"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookLibraryPathPartCatalogTests
{
private readonly BookLibraryPathPartCatalog _sut = new();
[Fact]
public void SupportedLibraryType_WhenCalled_ShouldReturnBook()
{
// Act
LibraryType result = _sut.SupportedLibraryType;
// Assert
Assert.Equal(LibraryType.Book, result);
}
[Fact]
public void GetPartDefinitions_WhenCalled_ShouldReturnTheExpectedDefinitions()
{
// Act
IReadOnlyList<LibraryPathPartDefinition> result = _sut.GetPartDefinitions();
// Assert
Assert.Equal(8, result.Count);
Assert.Equal(LibraryPathPartKind.Literal, result[0].Kind);
Assert.Equal(LibraryPathValueType.None, result[0].ValueType);
Assert.Equal(string.Empty, result[0].DefaultRepresentation);
Assert.False(result[0].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(LibraryPathValueType.None, result[1].ValueType);
Assert.Equal(string.Empty, result[1].DefaultRepresentation);
Assert.False(result[1].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Author, result[2].Kind);
Assert.Equal(LibraryPathValueType.Text, result[2].ValueType);
Assert.Equal("{0}", result[2].DefaultRepresentation);
Assert.False(result[2].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Title, result[3].Kind);
Assert.Equal(LibraryPathValueType.Text, result[3].ValueType);
Assert.Equal("{0}", result[3].DefaultRepresentation);
Assert.False(result[3].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Series, result[4].Kind);
Assert.Equal(LibraryPathValueType.Text, result[4].ValueType);
Assert.Equal("{0}", result[4].DefaultRepresentation);
Assert.True(result[4].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.SeriesNumber, result[5].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[5].ValueType);
Assert.Equal("{0}", result[5].DefaultRepresentation);
Assert.True(result[5].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.BookId, result[6].Kind);
Assert.Equal(LibraryPathValueType.Integer, result[6].ValueType);
Assert.Equal("{0}", result[6].DefaultRepresentation);
Assert.False(result[6].IsOptionalByDefault);
Assert.Equal(LibraryPathPartKind.Extension, result[7].Kind);
Assert.Equal(LibraryPathValueType.Text, result[7].ValueType);
Assert.Equal("{0}", result[7].DefaultRepresentation);
Assert.False(result[7].IsOptionalByDefault);
}
[Fact]
public void GetDefaultTemplate_WhenCalled_ShouldReturnTheExpectedParts()
{
// Act
IReadOnlyList<LibraryPathPart> result = _sut.GetDefaultTemplate().Parts;
// Assert
Assert.Equal(12, result.Count);
Assert.Equal(LibraryPathPartKind.Author, result[0].Kind);
Assert.Equal("{0}", result[0].Representation);
Assert.False(result[0].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[1].Kind);
Assert.Equal(string.Empty, result[1].Representation);
Assert.False(result[1].IsOptional);
Assert.Equal(LibraryPathPartKind.Title, result[2].Kind);
Assert.Equal("{0}", result[2].Representation);
Assert.False(result[2].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[3].Kind);
Assert.Equal(" (", result[3].Representation);
Assert.False(result[3].IsOptional);
Assert.Equal(LibraryPathPartKind.BookId, result[4].Kind);
Assert.Equal("{0}", result[4].Representation);
Assert.False(result[4].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[5].Kind);
Assert.Equal(")", result[5].Representation);
Assert.False(result[5].IsOptional);
Assert.Equal(LibraryPathPartKind.Separator, result[6].Kind);
Assert.Equal(string.Empty, result[6].Representation);
Assert.False(result[6].IsOptional);
Assert.Equal(LibraryPathPartKind.Title, result[7].Kind);
Assert.Equal("{0}", result[7].Representation);
Assert.False(result[7].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[8].Kind);
Assert.Equal(" - ", result[8].Representation);
Assert.False(result[8].IsOptional);
Assert.Equal(LibraryPathPartKind.Author, result[9].Kind);
Assert.Equal("{0}", result[9].Representation);
Assert.False(result[9].IsOptional);
Assert.Equal(LibraryPathPartKind.Literal, result[10].Kind);
Assert.Equal(".", result[10].Representation);
Assert.False(result[10].IsOptional);
Assert.Equal(LibraryPathPartKind.Extension, result[11].Kind);
Assert.Equal("{0}", result[11].Representation);
Assert.False(result[11].IsOptional);
}
}
@@ -0,0 +1,134 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryPathTemplateParts;
using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management;
using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Primitives;
using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using NSubstitute;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests
{
private readonly IQueryHandler<GetLibraryPathTemplatePartsQuery, Result<LibraryPathTemplateCatalogResponse>> _mockHandler;
private readonly GetLibraryPathTemplatePartsEndpoint _sut;
private readonly GetLibraryPathTemplatePartsRequestFixture _getLibraryPathTemplatePartsRequestFixture = new();
private readonly LibraryPathTemplateCatalogResponseFixture _libraryPathTemplateCatalogResponseFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsEndpointTests()
{
_mockHandler = Substitute.For<IQueryHandler<GetLibraryPathTemplatePartsQuery, Result<LibraryPathTemplateCatalogResponse>>>();
_sut = Factory.Create<GetLibraryPathTemplatePartsEndpoint>(_mockHandler);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryPathTemplateCatalogResponse()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
CancellationToken cancellationToken = CancellationToken.None;
LibraryPathTemplateCatalogResponse expectedResponse = _libraryPathTemplateCatalogResponseFixture.Create();
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(expectedResponse));
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
Ok<LibraryPathTemplateCatalogResponse> okResult = Assert.IsType<Ok<LibraryPathTemplateCatalogResponse>>(result);
Assert.Equal(expectedResponse, okResult.Value);
}
[Fact]
public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnProblemResult()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "NotARealLibraryType");
CancellationToken cancellationToken = CancellationToken.None;
Error expectedError = Error.Validation("Library.UnknownLibraryType", "UnknownLibraryType");
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(expectedError);
// Act
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
// Assert
ProblemHttpResult problemDetails = Assert.IsType<ProblemHttpResult>(result);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
Assert.Equal("application/problem+json", problemDetails.ContentType);
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemDetails.ProblemDetails);
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
Assert.Equal("General.Validation", validationProblemDetails.Title);
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
Assert.NotNull(validationProblemDetails.Instance);
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
Assert.Single(validationProblemDetails.Errors);
Assert.Equal(new[] { "UnknownLibraryType" }, validationProblemDetails.Errors["Library.UnknownLibraryType"]);
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryPathTemplatePartsQueryToSender()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create(libraryType: "Music");
CancellationToken cancellationToken = CancellationToken.None;
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(Result.From(_libraryPathTemplateCatalogResponseFixture.Create()));
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockHandler.Received(1).HandleAsync(
Arg.Is<GetLibraryPathTemplatePartsQuery>(query => query.LibraryType == request.LibraryType),
Arg.Is(cancellationToken));
}
[Fact]
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _getLibraryPathTemplatePartsRequestFixture.Create();
CancellationTokenSource cts = new();
TaskCompletionSource<bool> operationStarted = new();
TaskCompletionSource<bool> cancellationRequested = new();
_mockHandler.HandleAsync(Arg.Any<GetLibraryPathTemplatePartsQuery>(), Arg.Any<CancellationToken>())
.Returns(callInfo => Task.Run(async () =>
{
operationStarted.SetResult(true);
await cancellationRequested.Task;
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
return Result.From(_libraryPathTemplateCatalogResponseFixture.Create());
}, callInfo.Arg<CancellationToken>()));
// Act
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
await operationStarted.Task;
cts.Cancel();
cancellationRequested.SetResult(true);
// Assert
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
}
}
@@ -0,0 +1,113 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Management;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Management.GetLibraryPathTemplateParts;
/// <summary>
/// Contains unit tests for the <see cref="GetLibraryPathTemplatePartsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryPathTemplatePartsEndpointTests
{
private readonly IApiHttpClient _mockApiHttpClient;
private readonly GetLibraryPathTemplatePartsEndpoint _sut;
private readonly GetLibraryPathTemplatePartsRequestFixture _requestFixture = new();
private readonly LibraryPathTemplateCatalogDtoFixture _catalogDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryPathTemplatePartsEndpointTests"/> class.
/// </summary>
public GetLibraryPathTemplatePartsEndpointTests()
{
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
_sut = Factory.Create<GetLibraryPathTemplatePartsEndpoint>(_mockApiHttpClient);
}
[Fact]
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnSuccessJsonWithCatalog()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create();
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
// Assert
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
JsonElement data = jsonDocument.RootElement.GetProperty("data");
JsonElement parts = data.GetProperty("parts");
JsonElement defaultTemplateParts = data.GetProperty("defaultTemplateParts");
Assert.Equal(catalog.Parts.Count, parts.GetArrayLength());
Assert.Equal(catalog.DefaultTemplateParts.Count, defaultTemplateParts.GetArrayLength());
JsonElement firstPart = parts[0];
Assert.Equal(catalog.Parts[0].Kind, firstPart.GetProperty("kind").GetString());
Assert.Equal(catalog.Parts[0].ValueType, firstPart.GetProperty("valueType").GetString());
Assert.Equal(catalog.Parts[0].DefaultRepresentation, firstPart.GetProperty("defaultRepresentation").GetString());
Assert.Equal(catalog.Parts[0].IsOptionalByDefault, firstPart.GetProperty("isOptionalByDefault").GetBoolean());
JsonElement firstDefaultTemplatePart = defaultTemplateParts[0];
Assert.Equal(catalog.DefaultTemplateParts[0].Kind, firstDefaultTemplatePart.GetProperty("kind").GetString());
Assert.Equal(catalog.DefaultTemplateParts[0].Representation, firstDefaultTemplatePart.GetProperty("representation").GetString());
Assert.Equal(catalog.DefaultTemplateParts[0].IsOptional, firstDefaultTemplatePart.GetProperty("isOptional").GetBoolean());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldRequestCatalogFromApiWithSubstitutedLibraryType()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create(libraryType: "Music");
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_LIBRARY_PATH_TEMPLATE_PARTS.Replace("{libraryType}", "Music")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenCalled_ShouldForwardCancellationTokenToApi()
{
// Arrange
GetLibraryPathTemplatePartsRequest request = _requestFixture.Create();
LibraryPathTemplateCatalogDto catalog = _catalogDtoFixture.Create();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;
_mockApiHttpClient.GetAsync<LibraryPathTemplateCatalogDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(catalog);
// Act
await _sut.ExecuteAsync(request, cancellationToken);
// Assert
await _mockApiHttpClient.Received(1).GetAsync<LibraryPathTemplateCatalogDto>(
Arg.Any<string>(),
Arg.Is(cancellationToken));
}
}