From 04927a95af9e9e3f688d077e317764e7bd2d8a7c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:17:29 -0700 Subject: [PATCH 1/7] Refactors metadata provider contracts to typed interfaces --- .../OpenLibraryServices.cs | 21 ++--- .../Core/Api/OpenLibraryHttpClient.cs | 30 +++++-- .../Core/Mapping/OpenLibraryMapper.cs | 10 +-- .../Core/OpenLibraryBookMetadataProvider.cs | 31 ++++--- .../Settings/OpenLibrarySettingsProvider.cs | 88 +++++++++++++++++++ ...tadataProvider.cs => IMetadataProvider.cs} | 20 ++--- ...Generic.cs => IMetadataProviderGeneric.cs} | 8 +- .../Core/DTO/Common/OtherMetadataLookupDto.cs | 12 +++ .../Common/OtherMetadataLookupDtoFixture.cs | 34 +++++++ ...ts.cs => IMetadataProviderGenericTests.cs} | 29 +++--- .../OpenLibraryServicesTests.cs | 35 ++++---- .../Core/Api/OpenLibraryHttpClientTests.cs | 51 +++++++---- .../OpenLibraryBookMetadataProviderTests.cs | 18 ++-- .../Core/OpenLibraryPluginTests.cs | 4 +- 14 files changed, 274 insertions(+), 117 deletions(-) create mode 100644 plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs rename src/Lumina.Plugins.Contracts/Core/Metadata/{IRemoteMetadataProvider.cs => IMetadataProvider.cs} (71%) rename src/Lumina.Plugins.Contracts/Core/Metadata/{IRemoteMetadataProviderGeneric.cs => IMetadataProviderGeneric.cs} (86%) create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDto.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDtoFixture.cs rename tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/{IRemoteMetadataProviderGenericTests.cs => IMetadataProviderGenericTests.cs} (85%) diff --git a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs index d102ba55..3505cf7c 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Common/DependencyInjection/OpenLibraryServices.cs @@ -8,8 +8,6 @@ using Lumina.Plugins.OpenLibrary.Core.Settings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; -using System.Collections.Generic; -using System.Threading; #endregion namespace Lumina.Plugins.OpenLibrary.Common.DependencyInjection; @@ -30,27 +28,20 @@ internal static class OpenLibraryServices { ArgumentNullException.ThrowIfNull(services); - // Build the runtime settings per scope, overlaying the settings persisted by the host over the defaults and the optional callback. + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback. services.TryAddScoped(serviceProvider => { - OpenLibrarySettingsDto openLibrarySettings = new(); - settingsCallback?.Invoke(openLibrarySettings); + OpenLibrarySettingsDto defaults = new(); + settingsCallback?.Invoke(defaults); IPluginSettingsStore? settingsStore = serviceProvider.GetService(); - if (settingsStore is not null) - { - IReadOnlyDictionary? storedSettings = settingsStore.GetSettingsAsync(pluginId, CancellationToken.None).GetAwaiter().GetResult(); - if (storedSettings is not null) - OpenLibrarySettingsLoader.Apply(openLibrarySettings, storedSettings); - } - - return openLibrarySettings; + return new OpenLibrarySettingsProvider(settingsStore, pluginId, defaults); }); services.AddHttpClient(); - // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IRemoteMetadataProvider implementations. - services.AddKeyedTransient(pluginId); + // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations. + services.AddKeyedTransient(pluginId); return services; } diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs index 7749f4a2..e5a606a8 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Api/OpenLibraryHttpClient.cs @@ -3,6 +3,7 @@ using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Core.Mapping; +using Lumina.Plugins.OpenLibrary.Core.Settings; using System; using System.Collections.Generic; using System.Globalization; @@ -25,7 +26,7 @@ namespace Lumina.Plugins.OpenLibrary.Core.Api; internal sealed class OpenLibraryHttpClient { private readonly HttpClient _httpClient; - private readonly OpenLibrarySettingsDto _openLibrarySettings; + private readonly OpenLibrarySettingsProvider _settingsProvider; private readonly SemaphoreSlim _requestGate = new(1, 1); private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; @@ -44,18 +45,26 @@ internal sealed class OpenLibraryHttpClient /// Initializes a new instance of the class. /// /// The used to send requests to the Open Library API. - /// The settings that configure the Open Library API requests. - public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsDto openLibrarySettings) + /// The provider of the settings that configure the Open Library API requests. + public OpenLibraryHttpClient(HttpClient httpClient, OpenLibrarySettingsProvider settingsProvider) { _httpClient = httpClient; - _openLibrarySettings = openLibrarySettings; + _settingsProvider = settingsProvider; _httpClient.BaseAddress ??= new("https://openlibrary.org/"); - if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) - _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(openLibrarySettings.UserAgent); + } - if (!string.IsNullOrWhiteSpace(openLibrarySettings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null) - _httpClient.DefaultRequestHeaders.From = openLibrarySettings.ContactEmail!; + /// + /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. + /// + /// The settings that configure the Open Library API requests. + private void EnsureRequestHeaders(OpenLibrarySettingsDto settings) + { + if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) + _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(settings.UserAgent); + + if (!string.IsNullOrWhiteSpace(settings.ContactEmail) && _httpClient.DefaultRequestHeaders.From is null) + _httpClient.DefaultRequestHeaders.From = settings.ContactEmail!; } /// @@ -214,10 +223,13 @@ internal sealed class OpenLibraryHttpClient /// The HTTP response message for the request. private async Task SendAsync(string relativeUrl, CancellationToken cancellationToken) { + OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + EnsureRequestHeaders(settings); + await _requestGate.WaitAsync(cancellationToken).ConfigureAwait(false); try { - DateTimeOffset earliestNextRequest = _lastRequestAt + _openLibrarySettings.MinimumRequestInterval; + DateTimeOffset earliestNextRequest = _lastRequestAt + settings.MinimumRequestInterval; TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; if (delay > TimeSpan.Zero) await Task.Delay(delay, cancellationToken).ConfigureAwait(false); diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs index 041f7146..04058a62 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Mapping/OpenLibraryMapper.cs @@ -30,7 +30,7 @@ internal static partial class OpenLibraryMapper /// /// Matches a volume number in a series or volume string. /// - [GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?\d+)\b", RegexOptions.IgnoreCase)] + [GeneratedRegex(@"\b(?:volume|vol\.?|book|no\.?|#)\s*(?\d+(?:\.\d+)?)\b", RegexOptions.IgnoreCase)] private static partial Regex VolumePattern(); /// @@ -111,8 +111,8 @@ internal static partial class OpenLibraryMapper editionRelease.Date?.Year ?? editionRelease.Year, NullIfWhiteSpace(releaseCountry), NullIfWhiteSpace(releaseVersion)), - genreNames.Select(name => new GenreDto(name)).ToList(), - subjects.Select(name => new TagDto(name)).ToList(), + [.. genreNames.Select(name => new GenreDto(name))], + [.. subjects.Select(name => new TagDto(name))], MapLanguage(currentLanguageCode), MapLanguage(originalLanguageCode), edition?.Publishers.FirstOrDefault() ?? fallback?.Publishers.FirstOrDefault(), @@ -347,14 +347,14 @@ internal static partial class OpenLibraryMapper /// /// The strings that may contain a volume number. /// The parsed volume number, or when no candidate contains one. - private static int? ParseVolumeNumber(params string?[] candidates) + private static float? ParseVolumeNumber(params string?[] candidates) { foreach (string? candidate in candidates) { if (string.IsNullOrWhiteSpace(candidate)) continue; Match match = VolumePattern().Match(candidate); - if (match.Success && int.TryParse(match.Groups["number"].Value, out int number)) + if (match.Success && float.TryParse(match.Groups["number"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float number)) return number; } return null; diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs index 570b837d..b247c5dd 100644 --- a/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/OpenLibraryBookMetadataProvider.cs @@ -7,6 +7,7 @@ using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Mapping; +using Lumina.Plugins.OpenLibrary.Core.Settings; using System; using System.Collections.Generic; using System.Linq; @@ -19,10 +20,10 @@ namespace Lumina.Plugins.OpenLibrary.Core; /// /// Provides book metadata from the Open Library by resolving lookups into book metadata DTOs. /// -internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider +internal sealed class OpenLibraryBookMetadataProvider : IMetadataProvider { private readonly OpenLibraryHttpClient _openLibraryHttpClient; - private readonly OpenLibrarySettingsDto _openLibrarySettings; + private readonly OpenLibrarySettingsProvider _settingsProvider; /// /// Gets the display name of the metadata provider. @@ -30,9 +31,9 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< public string Name => "Open Library"; /// - /// Gets the media library type this metadata provider supports. + /// Gets the media library types this metadata provider supports. /// - public LibraryType SupportedLibraryType => LibraryType.Book; + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book]; /// /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. @@ -43,11 +44,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< /// Initializes a new instance of the class. /// /// The HTTP client used to call the Open Library API. - /// The settings that configure the Open Library API requests. - public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsDto openLibrarySettings) + /// The provider of the settings that configure the Open Library API requests. + public OpenLibraryBookMetadataProvider(OpenLibraryHttpClient openLibraryHttpClient, OpenLibrarySettingsProvider settingsProvider) { _openLibraryHttpClient = openLibraryHttpClient; - _openLibrarySettings = openLibrarySettings; + _settingsProvider = settingsProvider; } /// @@ -60,6 +61,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< { ValidateLookup(bookMetadataLookup); + OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + if (!string.IsNullOrWhiteSpace(bookMetadataLookup.Isbn) || !string.IsNullOrWhiteSpace(bookMetadataLookup.OpenLibraryId)) { AddBookRequest? exactBookRequestMatch = await GetBookAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); @@ -90,11 +93,11 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< exactBookRequestMatch.ISBNs, exactBookRequestMatch.Contributors, exactBookRequestMatch.Ratings, - CoverImageUrl: null + CoverImagePath: null )]; } - IReadOnlyList openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, _openLibrarySettings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + IReadOnlyList openLibrarySearchDocuments = await _openLibraryHttpClient.SearchAsync(bookMetadataLookup, settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); return [.. openLibrarySearchDocuments .Where(openLibrarySearchDocument => !string.IsNullOrWhiteSpace(openLibrarySearchDocument.Title)) @@ -128,7 +131,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< addBookRequest.ISBNs, addBookRequest.Contributors, addBookRequest.Ratings, - CoverImageUrl: null + CoverImagePath: null ); })]; } @@ -169,7 +172,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< exactBookRequestMatch.ISBNs, exactBookRequestMatch.Contributors, exactBookRequestMatch.Ratings, - CoverImageUrl: null + CoverImagePath: null ); } @@ -183,6 +186,8 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< { ValidateLookup(bookMetadataLookup); + OpenLibrarySettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OpenLibraryEditionResponse? openLibraryEditionResponse = null; OpenLibraryWorkResponse? openLibraryWorkResponse = null; OpenLibrarySearchDocumentResponse? openLibrarySearchDocumentResponse = null; @@ -199,7 +204,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< // A work has no publisher-specific details on its own (no ISBN, page count, etc.), so we still need to pull it for its work-level fields (e.g. description, subjects). openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(olid, cancellationToken).ConfigureAwait(false); // A work can have many editions; SelectEdition picks the one that best matches the lookup criteria (language, format, etc.) instead of assuming the first result is right. - openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup); + openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(olid, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup); } else throw new ArgumentException("A book Open Library ID must be a work ID ending in W or an edition ID ending in M.", nameof(bookMetadataLookup)); @@ -221,7 +226,7 @@ internal sealed class OpenLibraryBookMetadataProvider : IRemoteMetadataProvider< if (workId is not null) { openLibraryWorkResponse = await _openLibraryHttpClient.GetWorkAsync(workId, cancellationToken).ConfigureAwait(false); - openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, _openLibrarySettings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup); + openLibraryEditionResponse = SelectEdition(await _openLibraryHttpClient.GetEditionsAsync(workId, settings.WorkEditionLimit, cancellationToken).ConfigureAwait(false), bookMetadataLookup); } if (openLibraryEditionResponse is null && searchResults[0].EditionKeys.Count > 0) diff --git a/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs new file mode 100644 index 00000000..931db570 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Core/Settings/OpenLibrarySettingsProvider.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Core.Settings; + +/// +/// Provides the runtime settings of the Open Library metadata plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class OpenLibrarySettingsProvider +{ + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly OpenLibrarySettingsDto _defaults; + private readonly SemaphoreSlim _gate = new(1, 1); + private OpenLibrarySettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public OpenLibrarySettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, OpenLibrarySettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + OpenLibrarySettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + runtimeSettings = Clone(_defaults); + if (_settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is not null) + OpenLibrarySettingsLoader.Apply(runtimeSettings, storedSettings); + } + + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } + + /// + /// Creates a copy of the given runtime settings. + /// + /// The runtime settings to copy. + /// A copy of the given runtime settings. + private static OpenLibrarySettingsDto Clone(OpenLibrarySettingsDto source) + { + return new OpenLibrarySettingsDto + { + UserAgent = source.UserAgent, + ContactEmail = source.ContactEmail, + SearchResultLimit = source.SearchResultLimit, + WorkEditionLimit = source.WorkEditionLimit, + MinimumRequestInterval = source.MinimumRequestInterval + }; + } +} diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs similarity index 71% rename from src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProvider.cs rename to src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs index c0d52ba1..aef276fc 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProvider.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProvider.cs @@ -9,9 +9,9 @@ using System.Threading.Tasks; namespace Lumina.Plugins.Contracts.Core.Metadata; /// -/// Contract for a plugin that provides metadata for media items from a remote source. +/// Contract for a plugin that provides metadata for media items. /// -public interface IRemoteMetadataProvider +public interface IMetadataProvider { /// /// Gets the display name of the metadata provider. @@ -19,9 +19,9 @@ public interface IRemoteMetadataProvider string Name { get; } /// - /// Gets the media library type this metadata provider supports. + /// Gets the media library types this metadata provider supports. /// - LibraryType SupportedLibraryType { get; } + IReadOnlyList SupportedLibraryTypes { get; } /// /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. @@ -29,18 +29,18 @@ public interface IRemoteMetadataProvider bool RequiresWebAccess { get; } /// - /// Searches for the metadata of the media item described by . + /// Searches for the metadata of the media item described by . /// - /// The lookup describing the media item to search for. + /// The lookup describing the media item to search for. /// Cancellation token that can be used to stop the execution. /// The collection of metadata candidates found for the media item. - Task> GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); + Task> GetSearchResultsAsync(MetadataLookupDto metadataLookup, CancellationToken cancellationToken); /// - /// Gets the metadata of the media item described by . + /// Gets the metadata of the media item described by . /// - /// The lookup describing the media item to get the metadata for. + /// The lookup describing the media item to get the metadata for. /// Cancellation token that can be used to stop the execution. /// The metadata of the media item, or when no metadata was found. - Task GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); + Task GetMetadataAsync(MetadataLookupDto metadataLookup, CancellationToken cancellationToken); } diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs similarity index 86% rename from src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProviderGeneric.cs rename to src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs index 4d70f44d..980a4d9e 100644 --- a/src/Lumina.Plugins.Contracts/Core/Metadata/IRemoteMetadataProviderGeneric.cs +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IMetadataProviderGeneric.cs @@ -8,11 +8,11 @@ using System.Threading.Tasks; namespace Lumina.Plugins.Contracts.Core.Metadata; /// -/// Contract for a plugin that provides metadata for media items from a remote source, typed to the media item lookup and metadata types. +/// Contract for a plugin that provides metadata for media items, typed to the media item lookup and metadata types. /// /// The type of the lookup describing the media item. /// The type of the metadata of the media item. -public interface IRemoteMetadataProvider : IRemoteMetadataProvider +public interface IMetadataProvider : IMetadataProvider where TLookup : MetadataLookupDto where TMetadata : MetadataDto { @@ -38,7 +38,7 @@ public interface IRemoteMetadataProvider : IRemoteMetadataPr /// The lookup describing the media item to search for. /// Cancellation token that can be used to stop the execution. /// The collection of metadata candidates found for the media item. - async Task> IRemoteMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + async Task> IMetadataProvider.GetSearchResultsAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { return await GetSearchResultsAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); } @@ -49,7 +49,7 @@ public interface IRemoteMetadataProvider : IRemoteMetadataPr /// The lookup describing the media item to get the metadata for. /// Cancellation token that can be used to stop the execution. /// The metadata of the media item, or when no metadata was found. - async Task IRemoteMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + async Task IMetadataProvider.GetMetadataAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) { return await GetMetadataAsync((TLookup)lookup, cancellationToken).ConfigureAwait(false); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDto.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDto.cs new file mode 100644 index 00000000..33048f53 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDto.cs @@ -0,0 +1,12 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Test double deriving from for a runtime type other than . +/// +[ExcludeFromCodeCoverage] +public sealed record OtherMetadataLookupDto : MetadataLookupDto; diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDtoFixture.cs new file mode 100644 index 00000000..183e3439 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/OtherMetadataLookupDtoFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class OtherMetadataLookupDtoFixture +{ + /// + /// Creates a . + /// + /// The created . + public OtherMetadataLookupDto Create() + { + return new OtherMetadataLookupDto(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs similarity index 85% rename from tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs rename to tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs index 51d25183..6411a257 100644 --- a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IMetadataProviderGenericTests.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.Contracts.Core.Metadata; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -15,13 +15,14 @@ using System.Threading.Tasks; namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; /// -/// Contains unit tests for the interface. +/// Contains unit tests for the interface. /// [ExcludeFromCodeCoverage] -public class IRemoteMetadataProviderGenericTests +public class IMetadataProviderGenericTests { private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new(); [Fact] public async Task GetSearchResultsAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() @@ -31,7 +32,7 @@ public class IRemoteMetadataProviderGenericTests CancellationToken cancellationToken = CancellationToken.None; BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false); TestBookMetadataProvider provider = new(expectedMetadata); - IRemoteMetadataProvider baseProvider = provider; + IMetadataProvider baseProvider = provider; // Act IReadOnlyList result = await baseProvider.GetSearchResultsAsync(lookup, cancellationToken); @@ -51,7 +52,7 @@ public class IRemoteMetadataProviderGenericTests CancellationToken cancellationToken = CancellationToken.None; BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false); TestBookMetadataProvider provider = new(expectedMetadata); - IRemoteMetadataProvider baseProvider = provider; + IMetadataProvider baseProvider = provider; // Act MetadataDto? result = await baseProvider.GetMetadataAsync(lookup, cancellationToken); @@ -66,9 +67,9 @@ public class IRemoteMetadataProviderGenericTests public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() { // Arrange - MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); + MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false)); - IRemoteMetadataProvider baseProvider = provider; + IMetadataProvider baseProvider = provider; // Act async Task Act() @@ -85,9 +86,9 @@ public class IRemoteMetadataProviderGenericTests public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() { // Arrange - MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); + MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false)); - IRemoteMetadataProvider baseProvider = provider; + IMetadataProvider baseProvider = provider; // Act async Task Act() @@ -104,7 +105,7 @@ public class IRemoteMetadataProviderGenericTests /// Test double for the typed metadata provider interface that records the forwarded arguments. /// [ExcludeFromCodeCoverage] - private sealed class TestBookMetadataProvider : IRemoteMetadataProvider + private sealed class TestBookMetadataProvider : IMetadataProvider { private readonly BookMetadataDto _metadata; @@ -131,7 +132,7 @@ public class IRemoteMetadataProviderGenericTests public string Name => "Test Provider"; /// - public LibraryType SupportedLibraryType => LibraryType.Book; + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book]; /// public bool RequiresWebAccess => false; @@ -152,10 +153,4 @@ public class IRemoteMetadataProviderGenericTests return Task.FromResult(_metadata); } } - - /// - /// Test double deriving from for a runtime type other than . - /// - [ExcludeFromCodeCoverage] - private sealed record OtherMetadataLookupDto : MetadataLookupDto; } diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs index 7e00dc7a..b2f7b60f 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs @@ -60,8 +60,8 @@ public class OpenLibraryServicesTests ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - Assert.NotNull(serviceProvider.GetKeyedService(pluginId)); - Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + Assert.NotNull(serviceProvider.GetKeyedService(pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); } [Fact] @@ -79,7 +79,7 @@ public class OpenLibraryServicesTests } [Fact] - public void AddOpenLibraryBookMetadataProvider_WhenSettingsCallbackIsProvided_ShouldApplyTheCallbackToTheRuntimeSettings() + public async Task AddOpenLibraryBookMetadataProvider_WhenSettingsCallbackIsProvided_ShouldApplyTheCallbackToTheRuntimeSettings() { // Arrange ServiceCollection services = new(); @@ -88,16 +88,17 @@ public class OpenLibraryServicesTests services.AddOpenLibraryBookMetadataProvider( pluginId: Guid.NewGuid(), settingsCallback: settings => settings.ContactEmail = "callback@example.com"); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService(); + OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); Assert.Equal("callback@example.com", settings.ContactEmail); Assert.Equal(10, settings.SearchResultLimit); } [Fact] - public void AddOpenLibraryBookMetadataProvider_WhenASettingsStoreIsRegistered_ShouldApplyTheStoredSettings() + public async Task AddOpenLibraryBookMetadataProvider_WhenASettingsStoreIsRegistered_ShouldApplyTheStoredSettings() { // Arrange Guid pluginId = Guid.NewGuid(); @@ -112,16 +113,17 @@ public class OpenLibraryServicesTests // Act services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService(); + OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); Assert.Equal(25, settings.SearchResultLimit); Assert.Equal(50, settings.WorkEditionLimit); } [Fact] - public void AddOpenLibraryBookMetadataProvider_WhenTheSettingsStoreReturnsNull_ShouldKeepTheDefaultSettings() + public async Task AddOpenLibraryBookMetadataProvider_WhenTheSettingsStoreReturnsNull_ShouldKeepTheDefaultSettings() { // Arrange Guid pluginId = Guid.NewGuid(); @@ -133,27 +135,30 @@ public class OpenLibraryServicesTests // Act services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + OpenLibrarySettingsProvider settingsProvider = serviceProvider.GetRequiredService(); + OpenLibrarySettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); Assert.Equal(10, settings.SearchResultLimit); Assert.Equal(50, settings.WorkEditionLimit); } [Fact] - public void AddOpenLibraryBookMetadataProvider_WhenResolvedAcrossScopes_ShouldReturnDistinctRuntimeSettingsInstances() + public async Task AddOpenLibraryBookMetadataProvider_WhenResolvedAcrossScopes_ShouldReturnDistinctRuntimeSettingsInstances() { // Arrange ServiceCollection services = new(); services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); - ServiceProvider serviceProvider = services.BuildServiceProvider(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); // Act using IServiceScope firstScope = serviceProvider.CreateScope(); using IServiceScope secondScope = serviceProvider.CreateScope(); - OpenLibrarySettingsDto first = firstScope.ServiceProvider.GetRequiredService(); - OpenLibrarySettingsDto second = secondScope.ServiceProvider.GetRequiredService(); + OpenLibrarySettingsProvider firstProvider = firstScope.ServiceProvider.GetRequiredService(); + OpenLibrarySettingsProvider secondProvider = secondScope.ServiceProvider.GetRequiredService(); + OpenLibrarySettingsDto first = await firstProvider.GetAsync(CancellationToken.None); + OpenLibrarySettingsDto second = await secondProvider.GetAsync(CancellationToken.None); // Assert Assert.NotSame(first, second); diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs index e06b5a33..c0e6f138 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs @@ -4,6 +4,7 @@ using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.Book using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Core.Api; +using Lumina.Plugins.OpenLibrary.Core.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup; using System; @@ -35,7 +36,7 @@ public class OpenLibraryHttpClientTests HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); // Act - _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); + _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create())); // Assert Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress); @@ -52,61 +53,72 @@ public class OpenLibraryHttpClientTests }; // Act - _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); + _ = new OpenLibraryHttpClient(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create())); // Assert Assert.Equal(existingBaseAddress, httpClient.BaseAddress); } [Fact] - public void Constructor_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent() + public async Task GetEditionAsync_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent() { // Arrange - HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); - OpenLibrarySettingsDto settings = _settingsFixture.Create(userAgent: "CustomAgent/2.0"); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); + HttpClient httpClient = new(handler); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "CustomAgent/2.0"))); // Act - _ = new OpenLibraryHttpClient(httpClient, settings); + await sut.GetEditionAsync("OL1M", CancellationToken.None); // Assert Assert.Equal("CustomAgent/2.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); } [Fact] - public void Constructor_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent() + public async Task GetEditionAsync_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent() { // Arrange - HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); + HttpClient httpClient = new(handler); httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0"); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0"))); // Act - _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0")); + await sut.GetEditionAsync("OL1M", CancellationToken.None); // Assert Assert.Equal("ExistingAgent/1.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); } [Fact] - public void Constructor_WhenContactEmailIsConfigured_ShouldSetTheFromHeader() + public async Task GetEditionAsync_WhenContactEmailIsConfigured_ShouldSetTheFromHeader() { // Arrange - HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); + HttpClient httpClient = new(handler); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: "contact@example.com"))); // Act - _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: "contact@example.com")); + await sut.GetEditionAsync("OL1M", CancellationToken.None); // Assert Assert.Equal("contact@example.com", httpClient.DefaultRequestHeaders.From); } [Fact] - public void Constructor_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader() + public async Task GetEditionAsync_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader() { // Arrange - HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL1M.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); + HttpClient httpClient = new(handler); + OpenLibraryHttpClient sut = new(httpClient, new OpenLibrarySettingsProvider(null, Guid.NewGuid(), _settingsFixture.Create(contactEmail: null))); // Act - _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: null)); + await sut.GetEditionAsync("OL1M", CancellationToken.None); // Assert Assert.Null(httpClient.DefaultRequestHeaders.From); @@ -541,9 +553,16 @@ public class OpenLibraryHttpClientTests await Assert.ThrowsAnyAsync(Act); } + /// + /// Creates the Open Library HTTP client under test backed by the given handler and settings. + /// + /// The stub HTTP message handler used to serve responses. + /// Optional. The Open Library settings used by the client. When omitted, randomized settings are used. + /// The created . private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) { HttpClient httpClient = new(handler); - return new OpenLibraryHttpClient(httpClient, settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + return new OpenLibraryHttpClient(httpClient, settingsProvider); } } diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs index 5b3a6665..8d43ba9e 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs @@ -7,12 +7,12 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Core; using Lumina.Plugins.OpenLibrary.Core.Api; +using Lumina.Plugins.OpenLibrary.Core.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; using Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -30,13 +30,9 @@ public class OpenLibraryBookMetadataProviderTests private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); private const string EDITION_JSON = """{"key":"/books/OL100M","title":"Edition Title","publish_date":"2010-05-01","number_of_pages":320,"physical_format":"Hardcover","edition_name":"First Edition","series":["The Series"],"volume":"Vol. 3","publishers":["Publisher Co"],"isbn_13":["9780306406157"],"languages":[{"key":"/languages/eng"}],"works":[{"key":"/works/OL200W"}]}"""; - private const string WORK_JSON = """{"key":"/works/OL200W","title":"Work Title","first_publish_date":"2001-01-01","description":{"value":"A work description"},"subjects":["Science fiction"],"authors":[{"author":{"key":"/authors/OL1A"}}]}"""; - private const string AUTHOR_JSON = """{"key":"/authors/OL1A","name":"Test Author"}"""; - private const string RATINGS_JSON = """{"summary":{"average":4.2,"count":100}}"""; - private const string EDITIONS_JSON = """{"entries":[{"key":"/books/OL100M","title":"Edition Title","languages":[{"key":"/languages/eng"}]}]}"""; [Fact] @@ -53,16 +49,17 @@ public class OpenLibraryBookMetadataProviderTests } [Fact] - public void SupportedLibraryType_WhenCalled_ShouldReturnBook() + public void SupportedLibraryTypes_WhenCalled_ShouldReturnBook() { // Arrange OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); // Act - LibraryType result = sut.SupportedLibraryType; + IReadOnlyList result = sut.SupportedLibraryTypes; // Assert - Assert.Equal(LibraryType.Book, result); + Assert.Single(result); + Assert.Equal(LibraryType.Book, result[0]); } [Fact] @@ -442,7 +439,8 @@ public class OpenLibraryBookMetadataProviderTests private OpenLibraryBookMetadataProvider CreateProvider(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) { OpenLibrarySettingsDto runtimeSettings = settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero); - OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), runtimeSettings); - return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, runtimeSettings); + OpenLibrarySettingsProvider settingsProvider = new(null, Guid.NewGuid(), runtimeSettings); + OpenLibraryHttpClient openLibraryHttpClient = new(new HttpClient(handler), settingsProvider); + return new OpenLibraryBookMetadataProvider(openLibraryHttpClient, settingsProvider); } } diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs index a3df9bde..d9086513 100644 --- a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs @@ -2,7 +2,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; using Lumina.Plugins.Contracts.Core.Metadata; -using Lumina.Plugins.OpenLibrary.Common.DependencyInjection; using Lumina.Plugins.OpenLibrary.Core; using Lumina.Plugins.OpenLibrary.Core.Api; using Lumina.Plugins.OpenLibrary.Core.Settings; @@ -10,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Plugins.OpenLibrary.UnitTests.Core; @@ -131,7 +129,7 @@ public class OpenLibraryPluginTests ServiceProvider serviceProvider = services.BuildServiceProvider(); // Assert - Assert.NotNull(serviceProvider.GetKeyedService(OpenLibraryPlugin.s_pluginId)); + Assert.NotNull(serviceProvider.GetKeyedService(OpenLibraryPlugin.s_pluginId)); Assert.NotNull(serviceProvider.GetService()); } } From 6693ff3f60d79e8e1992e63ee8a43b51d0d6fdfc Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:18:14 -0700 Subject: [PATCH 2/7] Adds artwork provider system and Calibre plugin --- Directory.Packages.props | 1 + .../DependencyInjection/CalibreServices.cs | 46 + .../Models/DTO/Opf/OpfContributorDto.cs | 17 + .../Common/Models/DTO/Opf/OpfCreatorDto.cs | 17 + .../Common/Models/DTO/Opf/OpfDocumentDto.cs | 79 + .../Common/Models/DTO/Opf/OpfIdentifierDto.cs | 17 + .../Core/CalibreArtworkProvider.cs | 67 + .../Core/CalibreBookMetadataProvider.cs | 75 + .../Core/CalibrePlugin.cs | 65 + .../Core/Mapping/CalibreMapper.cs | 242 +++ .../Core/Opf/OpfReader.cs | 158 ++ .../Lumina.Plugins.Calibre.csproj | 32 + .../Properties/AssemblyInfo.cs | 4 + .../BookLibrary/BookEntity.cs | 7 +- ...braryArtworkProviderConfigurationEntity.cs | 59 + ...IArtworkProviderConfigurationRepository.cs | 42 + .../BookLibrary/Books/BookEntityMapping.cs | 17 +- .../BookLibrary/Books/BookMapping.cs | 1 + .../Books/BookMetadataDtoMapping.cs | 12 +- .../Books/GetBooksLiteRequestMapping.cs | 5 +- ...etLibraryArtworkProvidersRequestMapping.cs | 22 + ...tworkProviderConfigurationEntityMapping.cs | 28 + ...erLibraryArtworkProvidersRequestMapping.cs | 25 + ...aryArtworkProviderEnabledRequestMapping.cs | 26 + .../Common/Utilities/ValidatorUtilities.cs | 27 + .../Artwork/IBookArtworkService.cs | 39 + .../Books/Commands/AddBook/AddBookCommand.cs | 8 +- .../AddBook/AddBookCommandValidator.cs | 5 +- .../ReorderLibraryArtworkProvidersCommand.cs | 17 + ...erLibraryArtworkProvidersCommandHandler.cs | 92 ++ ...LibraryArtworkProvidersCommandValidator.cs | 32 + ...SetLibraryArtworkProviderEnabledCommand.cs | 18 + ...aryArtworkProviderEnabledCommandHandler.cs | 107 ++ ...yArtworkProviderEnabledCommandValidator.cs | 32 + .../GetLibraryArtworkProvidersQuery.cs | 14 + .../GetLibraryArtworkProvidersQueryHandler.cs | 88 ++ ...etLibraryArtworkProvidersQueryValidator.cs | 26 + src/Lumina.Contracts/DTO/Common/ArtworkDto.cs | 16 + .../BookLibrary/BookMetadataDto.cs | 6 +- .../BookLibrary/Books/AddBookRequest.cs | 2 +- .../BookLibrary/Books/GetBooksLiteRequest.cs | 4 +- .../GetLibraryArtworkProvidersRequest.cs | 15 + .../ReorderLibraryArtworkProvidersRequest.cs | 18 + ...SetLibraryArtworkProviderEnabledRequest.cs | 19 + .../BookLibrary/Books/BookResponse.cs | 6 +- .../Plugins/LibraryArtworkProviderResponse.cs | 19 + ...tworkProviderConfigurationConfiguration.cs | 57 + ...ookCoverAndMetadataAggregation.Designer.cs | 1358 +++++++++++++++++ ...idersAndBookCoverAndMetadataAggregation.cs | 106 ++ .../LuminaDbContextModelSnapshot.cs | 76 +- .../ArtworkProviderConfigurationRepository.cs | 80 + .../Enums/BookLibrary/BookRatingSource.cs | 5 + .../BookLibraryAggregate/Book.cs | 27 +- .../Scanners/BookLibraryTypeScanner.cs | 17 +- .../InfrastructureLayerServices.cs | 6 + .../Artwork/BookArtworkService.cs | 337 ++++ .../Lumina.Infrastructure.csproj | 1 + .../Core/Metadata/IArtworkProvider.cs | 38 + .../Core/Metadata/IArtworkProviderGeneric.cs | 34 + .../PresentationApiLayerServices.cs | 9 +- .../Library/Management/ApiRoutes.Libraries.cs | 3 + .../Books/AddBook/AddBookEndpointSummary.cs | 13 +- .../Books/GetBooks/GetBooksEndpointSummary.cs | 6 +- .../GetBooksLiteEndpointSummary.cs | 4 +- .../GetLibraryArtworkProvidersEndpoint.cs | 56 + ...tLibraryArtworkProvidersEndpointSummary.cs | 130 ++ .../ReorderLibraryArtworkProvidersEndpoint.cs | 53 + ...rLibraryArtworkProvidersEndpointSummary.cs | 116 ++ ...etLibraryArtworkProviderEnabledEndpoint.cs | 53 + ...ryArtworkProviderEnabledEndpointSummary.cs | 113 ++ src/Lumina.Presentation.Api/Program.cs | 8 +- .../BookLibrary/BookDto.cs | 2 +- .../Enums/BookLibrary/BookRatingSource.cs | 5 + .../Requests/Libraries/GetBooksLiteRequest.cs | 2 +- .../Common/Utilities/ValidatorUtilities.cs | 27 + .../GetLibraryItemsEndpoint.cs | 3 +- .../GetLibraryItemsEndpointSummary.cs | 3 +- .../BookLibrary/Books/Index.cshtml | 4 +- src/Lumina.sln | 45 + ...tworkProviderConfigurationEntityFixture.cs | 57 + ...erLibraryArtworkProvidersCommandFixture.cs | 46 + ...aryArtworkProviderEnabledCommandFixture.cs | 50 + .../GetLibraryArtworkProvidersQueryFixture.cs | 41 + .../Core/DTO/Common/ArtworkDtoFixture.cs | 38 + ...etLibraryArtworkProvidersRequestFixture.cs | 42 + ...erLibraryArtworkProvidersRequestFixture.cs | 45 + ...aryArtworkProviderEnabledRequestFixture.cs | 48 + .../LibraryArtworkProviderResponseFixture.cs | 50 + .../Common/Setup/StubHttpMessageHandler.cs | 55 + .../DTO/Opf/OpfContributorDtoFixture.cs | 38 + .../Models/DTO/Opf/OpfCreatorDtoFixture.cs | 38 + .../Models/DTO/Opf/OpfDocumentDtoFixture.cs | 81 + .../Models/DTO/Opf/OpfIdentifierDtoFixture.cs | 38 + .../Core/Metadata/TestMetadataLookup.cs | 13 + .../Metadata/TestMetadataLookupFixture.cs | 38 + .../Lumina.Plugins.Calibre.Fixtures.csproj | 26 + .../Properties/AssemblyInfo.cs | 20 + ...GetLibraryArtworkProvidersEndpointTests.cs | 153 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 140 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 156 ++ ...GetLibraryArtworkProvidersEndpointTests.cs | 119 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 133 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 126 ++ .../BookArtworkServiceSecurityTests.cs | 236 +++ .../CalibreArtworkProviderSecurityTests.cs | 110 ++ .../Calibre/Opf/OpfReaderSecurityTests.cs | 155 ++ ...raryArtworkProvidersCommandHandlerTests.cs | 183 +++ ...ryArtworkProvidersCommandValidatorTests.cs | 104 ++ ...tworkProviderEnabledCommandHandlerTests.cs | 242 +++ ...orkProviderEnabledCommandValidatorTests.cs | 89 ++ ...ibraryArtworkProvidersQueryHandlerTests.cs | 231 +++ ...raryArtworkProvidersQueryValidatorTests.cs | 49 + ...orkProviderConfigurationRepositoryTests.cs | 137 ++ .../Artwork/BookArtworkServiceTests.cs | 541 +++++++ .../Core/CalibreArtworkProviderTests.cs | 252 +++ .../Core/CalibreBookMetadataProviderTests.cs | 174 +++ .../Core/CalibrePluginTests.cs | 98 ++ .../Core/Mapping/CalibreMapperTests.cs | 367 +++++ .../Core/Opf/OpfReaderTests.cs | 212 +++ .../Lumina.Plugins.Calibre.UnitTests.csproj | 48 + .../Metadata/IArtworkProviderGenericTests.cs | 105 ++ ...GetLibraryArtworkProvidersEndpointTests.cs | 136 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 129 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 129 ++ 124 files changed, 9715 insertions(+), 74 deletions(-) create mode 100644 plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj create mode 100644 plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs create mode 100644 src/Lumina.Contracts/DTO/Common/ArtworkDto.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs create mode 100644 src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs create mode 100644 src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs create mode 100644 tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj create mode 100644 tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index f98f56c2..7f669fa1 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -33,6 +33,7 @@ + diff --git a/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs new file mode 100644 index 00000000..20b7b97f --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Plugins.Calibre.Common.DependencyInjection; + +/// +/// Provides extension methods for registering the Calibre metadata and artwork providers. +/// +internal static class CalibreServices +{ + /// + /// Registers the Calibre book metadata provider, associated with the plugin that provides it. + /// + /// The service collection to register the services into. + /// The unique identifier of the plugin that provides the metadata. + /// The service collection, for chaining. + internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } + + /// + /// Registers the Calibre artwork provider, associated with the plugin that provides it. + /// + /// The service collection to register the services into. + /// The unique identifier of the plugin that provides the artwork. + /// The service collection, for chaining. + internal static IServiceCollection AddCalibreArtworkProvider(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs new file mode 100644 index 00000000..fb72a220 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for a contributor of a book read from an OPF file. +/// +/// The name of the contributor. +/// The role code of the contributor, for example bkp for the book producer. +[DebuggerDisplay("Name: {Name}")] +internal sealed record OpfContributorDto( + string Name, + string? Role +); diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs new file mode 100644 index 00000000..2f79c0f8 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for a creator of a book read from an OPF file. +/// +/// The name of the creator. +/// The role code of the creator, for example aut for author. +[DebuggerDisplay("Name: {Name}")] +internal sealed record OpfCreatorDto( + string Name, + string? Role +); diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs new file mode 100644 index 00000000..a49ca5e6 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for the metadata read from a Calibre OPF file. +/// +[DebuggerDisplay("Title: {Title}")] +internal sealed class OpfDocumentDto +{ + /// + /// Gets or sets the title of the book. + /// + public string? Title { get; set; } + + /// + /// Gets or sets the description of the book, in HTML format. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the publisher of the book. + /// + public string? Publisher { get; set; } + + /// + /// Gets or sets the publication date of the book. + /// + public DateTimeOffset? PublishDate { get; set; } + + /// + /// Gets or sets the language code of the book. + /// + public string? LanguageCode { get; set; } + + /// + /// Gets or sets the name of the series the book belongs to, if applicable. + /// + public string? Series { get; set; } + + /// + /// Gets or sets the index of the book within its series, if applicable. + /// + public double? SeriesIndex { get; set; } + + /// + /// Gets or sets the personal rating of the book, on a scale of 0 to 10. + /// + public int? Rating { get; set; } + + /// + /// Gets or sets the href of the cover image, relative to the directory of the book. + /// + public string? CoverHref { get; set; } + + /// + /// Gets the creators of the book. + /// + public List Creators { get; } = []; + + /// + /// Gets the contributors of the book. + /// + public List Contributors { get; } = []; + + /// + /// Gets the identifiers of the book, with their schemes. + /// + public List Identifiers { get; } = []; + + /// + /// Gets the subjects of the book, used as tags. + /// + public List Subjects { get; } = []; +} diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs new file mode 100644 index 00000000..1d10d643 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for an identifier of a book read from an OPF file, with its scheme. +/// +/// The scheme of the identifier, for example ISBN or GOODREADS. +/// The value of the identifier. +[DebuggerDisplay("{Scheme}: {Value}")] +internal sealed record OpfIdentifierDto( + string Scheme, + string Value +); diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs new file mode 100644 index 00000000..e3ffd5e3 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Provides the cover of a book from the cover reference of the Calibre OPF file located next to the book file. +/// +internal sealed class CalibreArtworkProvider : IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Calibre"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Gets the cover of the book described by . + /// + /// The lookup describing the book to get the cover for. + /// Cancellation token that can be used to stop the execution. + /// The cover of the book, or when no cover was found. + public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Path)) + return Task.FromResult(null); + + string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty; + string opfFilePath = Path.Combine(bookDirectory, "metadata.opf"); + if (!File.Exists(opfFilePath)) + return Task.FromResult(null); + + OpfDocumentDto document = OpfReader.Read(opfFilePath); + if (string.IsNullOrWhiteSpace(document.CoverHref)) + return Task.FromResult(null); + + // the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed + string coverFileName = Path.GetFileName(document.CoverHref); + if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref)) + return Task.FromResult(null); + + string coverFilePath = Path.Combine(bookDirectory, coverFileName); + if (!File.Exists(coverFilePath)) + return Task.FromResult(null); + + return Task.FromResult(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null)); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs new file mode 100644 index 00000000..950ddcab --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core.Mapping; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs. +/// +internal sealed class CalibreBookMetadataProvider : IMetadataProvider +{ + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "Calibre"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Searches for the metadata of the media item described by . + /// + /// The lookup describing the media item to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of metadata candidates found for the media item. + public Task> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + BookMetadataDto? metadata = GetMetadata(bookMetadataLookup); + return Task.FromResult>(metadata is null ? [] : [metadata]); + } + + /// + /// Gets the metadata of the media item described by . + /// + /// The lookup describing the media item to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the media item, or when no metadata was found. + public Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + return Task.FromResult(GetMetadata(bookMetadataLookup)); + } + + /// + /// Reads the metadata of the book from the OPF file located next to the book file described by . + /// + /// The lookup describing the book to get the metadata for. + /// The metadata of the book, or when no OPF file was found. + private static BookMetadataDto? GetMetadata(BookMetadataLookupDto bookMetadataLookup) + { + if (string.IsNullOrWhiteSpace(bookMetadataLookup.Path)) + return null; + + string opfFilePath = Path.Combine(Path.GetDirectoryName(bookMetadataLookup.Path) ?? string.Empty, "metadata.opf"); + if (!File.Exists(opfFilePath)) + return null; + + return CalibreMapper.Map(OpfReader.Read(opfFilePath)); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs new file mode 100644 index 00000000..10138ea1 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Calibre.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Plugin that provides book metadata and book covers from Calibre OPF files. +/// +public sealed class CalibrePlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Calibre Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Reads book metadata and covers from the OPF files of a Calibre library."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddCalibreBookMetadataProvider(pluginId: Id); + services.AddCalibreArtworkProvider(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs new file mode 100644 index 00000000..60c2dc54 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Plugins.Calibre.Core.Mapping; + +/// +/// Maps the metadata read from a Calibre OPF file into the application's book metadata DTO. +/// +internal static class CalibreMapper +{ + /// + /// Maps the metadata read from the OPF file into a book metadata DTO. + /// + /// The metadata read from the OPF file. + /// The mapped book metadata. + public static BookMetadataDto Map(OpfDocumentDto document) + { + float? volumeNumber = document.SeriesIndex is > 0 ? (float?)document.SeriesIndex : null; + + return new BookMetadataDto( + Title: document.Title, + OriginalTitle: null, + Description: StripHtml(document.Description), + ReleaseInfo: BuildReleaseInfo(document.PublishDate), + Genres: null, + Tags: [.. document.Subjects.Select(subject => new TagDto(Name: subject))], + Language: MapLanguage(document.LanguageCode), + OriginalLanguage: null, + Publisher: document.Publisher, + PageCount: null, + Format: null, + Edition: null, + VolumeNumber: volumeNumber, + Series: document.Series is null ? null : new BookSeriesDto(Title: document.Series), + ASIN: GetIdentifier(document.Identifiers, "asin", "amazon"), + GoodreadsId: GetIdentifier(document.Identifiers, "goodreads"), + LCCN: GetIdentifier(document.Identifiers, "lccn"), + OCLCNumber: GetIdentifier(document.Identifiers, "oclc"), + OpenLibraryId: GetIdentifier(document.Identifiers, "openlibrary"), + LibraryThingId: null, + GoogleBooksId: GetIdentifier(document.Identifiers, "google", "googlebooks"), + BarnesAndNobleId: null, + AppleBooksId: null, + Isbns: BuildIsbns(document.Identifiers), + Contributors: BuildContributors(document.Creators, document.Contributors), + Ratings: document.Rating is null ? null : [new BookRatingDto(Value: document.Rating, MaxValue: 10m, Source: BookRatingSource.Calibre, VoteCount: null)], + CoverImagePath: null + ); + } + + /// + /// Builds the release information of the book from its publication date. + /// + /// The publication date of the book. + /// The release information of the book, always present even when the publication date is missing. + private static ReleaseInfoDto BuildReleaseInfo(DateTimeOffset? publishDate) + { + // the release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book + if (publishDate is null) + { + return new ReleaseInfoDto( + OriginalReleaseDate: null, + OriginalReleaseYear: null, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null + ); + } + + DateOnly? releaseDate = DateOnly.FromDateTime(publishDate.Value.Date); + return new ReleaseInfoDto( + OriginalReleaseDate: releaseDate, + OriginalReleaseYear: releaseDate?.Year, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null + ); + } + + /// + /// Maps the ISBN identifiers of the book into ISBN DTOs, de-duplicating normalized values. + /// + /// The identifiers read from the OPF file. + /// The mapped and de-duplicated ISBN DTOs. + private static List BuildIsbns(List identifiers) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + foreach (OpfIdentifierDto identifier in identifiers.Where(identifier => string.Equals(identifier.Scheme, "isbn", StringComparison.OrdinalIgnoreCase))) + { + string? normalized = NormalizeIsbn(identifier.Value); + if (normalized is null || !seen.Add(normalized)) + continue; + result.Add(new IsbnDto(Value: normalized, Format: normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13)); + } + + return result; + } + + /// + /// Maps the creators and contributors of the book into contributor DTOs, de-duplicating identical name and role pairs. + /// + /// The creators read from the OPF file. + /// The contributors read from the OPF file. + /// The mapped contributor DTOs. + private static List BuildContributors(List creators, List contributors) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + void Add(string? displayName, string role, string category) + { + if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) + return; + result.Add(new MediaContributorDto( + Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null), + Role: new MediaContributorRoleDto(Name: role, Category: category)) + ); + } + + foreach (OpfCreatorDto creator in creators) + Add(creator.Name, "Author", "Writing"); + foreach (OpfContributorDto contributor in contributors) + Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role)); + + return result; + } + + /// + /// Maps a language code into a language info DTO by matching it against known cultures. + /// + /// The raw language code to map. + /// The mapped language info, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + IEnumerable cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures) + .Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures)); + + CultureInfo? culture = cultures.FirstOrDefault(candidate => + string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) || + string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase)); + + return culture is null + ? new LanguageInfoDto(LanguageCode: code, LanguageName: code, NativeName: null) + : new LanguageInfoDto(LanguageCode: culture.TwoLetterISOLanguageName, LanguageName: culture.EnglishName, NativeName: culture.NativeName); + } + + /// + /// Strips the HTML markup of a description, leaving the text content. + /// + /// The HTML value to strip. + /// The text content, or when the value is empty. + private static string? StripHtml(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + + string decoded = WebUtility.HtmlDecode(value); + string withoutTags = Regex.Replace(decoded, "<[^>]+>", " "); + string collapsed = Regex.Replace(withoutTags, @"\s+", " ").Trim(); + return collapsed.Length == 0 ? null : collapsed; + } + + /// + /// Normalizes an ISBN into its canonical form without separators or whitespace. + /// + /// The ISBN to normalize. + /// The normalized ISBN, or when the value is not a valid ISBN. + private static string? NormalizeIsbn(string isbn) + { + string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant(); + // valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10 + if ((normalized.Length != 10 && normalized.Length != 13) || + normalized[..^1].Any(character => !char.IsDigit(character)) || + (!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X'))) + return null; + + return normalized; + } + + /// + /// Gets the value of the first identifier whose scheme matches one of the . + /// + /// The identifiers read from the OPF file. + /// The identifier schemes to try, in order. + /// The identifier value, or when no identifier matches. + private static string? GetIdentifier(List identifiers, params string[] schemes) + { + foreach (OpfIdentifierDto identifier in identifiers) + if (schemes.Any(scheme => string.Equals(identifier.Scheme, scheme, StringComparison.OrdinalIgnoreCase))) + return identifier.Value; + + return null; + } + + /// + /// Maps a creator or contributor role code into a role name. + /// + /// The role code to map. + /// The mapped role name. + private static string MapContributorRole(string? role) + { + return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role; + } + + /// + /// Maps a creator or contributor role code into a contributor category. + /// + /// The role code to map. + /// The mapped contributor category. + private static string MapContributorCategory(string? role) + { + if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true) + return "Writing"; + if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase)) + return "Art"; + if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase)) + return "Translation"; + if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase)) + return "Production"; + return "Other"; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs new file mode 100644 index 00000000..cb776e35 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Core.Opf; + +/// +/// Reads the metadata of a book from a Calibre OPF file. +/// +internal static class OpfReader +{ + private const long MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private static readonly XNamespace s_opfNamespace = "http://www.idpf.org/2007/opf"; + private static readonly XNamespace s_dcNamespace = "http://purl.org/dc/elements/1.1/"; + + /// + /// Reads the metadata of the book from the OPF file at . + /// + /// The file system path of the OPF file to read. + /// The metadata read from the OPF file, with the fields that could not be read left empty. + public static OpfDocumentDto Read(string opfFilePath) + { + OpfDocumentDto document = new(); + FileInfo fileInfo = new(opfFilePath); + if (!fileInfo.Exists || fileInfo.Length > MAX_OPF_FILE_SIZE_BYTES) + return document; + + try + { + using FileStream fileStream = File.OpenRead(opfFilePath); + // the OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded + XmlReaderSettings xmlReaderSettings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersInDocument = MAX_OPF_FILE_SIZE_BYTES, + MaxCharactersFromEntities = 0 + }; + using XmlReader xmlReader = XmlReader.Create(fileStream, xmlReaderSettings); + XDocument xDocument = XDocument.Load(xmlReader, LoadOptions.None); + Parse(xDocument, document); + } + catch (XmlException) + { + // a malformed OPF file must not prevent the enrichment of the book from proceeding + } + + return document; + } + + /// + /// Parses the metadata elements of the into the . + /// + /// The parsed OPF document. + /// The model onto which the parsed metadata is written. + private static void Parse(XDocument xDocument, OpfDocumentDto document) + { + XElement? metadata = xDocument.Root?.Element(s_opfNamespace + "metadata"); + if (metadata is null) + return; + + document.Title = GetElementText(metadata, s_dcNamespace + "title"); + document.Description = GetElementText(metadata, s_dcNamespace + "description"); + document.Publisher = GetElementText(metadata, s_dcNamespace + "publisher"); + document.LanguageCode = GetElementText(metadata, s_dcNamespace + "language"); + document.PublishDate = ParseDate(GetElementText(metadata, s_dcNamespace + "date")); + + foreach (XElement identifier in metadata.Elements(s_dcNamespace + "identifier")) + { + string? scheme = identifier.Attribute(s_opfNamespace + "scheme")?.Value; + if (!string.IsNullOrWhiteSpace(scheme) && !string.IsNullOrWhiteSpace(identifier.Value)) + document.Identifiers.Add(new OpfIdentifierDto(Scheme: scheme.Trim(), Value: identifier.Value.Trim())); + } + + foreach (XElement subject in metadata.Elements(s_dcNamespace + "subject")) + if (!string.IsNullOrWhiteSpace(subject.Value)) + document.Subjects.Add(subject.Value.Trim()); + + foreach (XElement creator in metadata.Elements(s_dcNamespace + "creator")) + if (!string.IsNullOrWhiteSpace(creator.Value)) + document.Creators.Add(new OpfCreatorDto(Name: creator.Value.Trim(), Role: creator.Attribute(s_opfNamespace + "role")?.Value?.Trim())); + + foreach (XElement contributor in metadata.Elements(s_dcNamespace + "contributor")) + if (!string.IsNullOrWhiteSpace(contributor.Value)) + document.Contributors.Add(new OpfContributorDto(Name: contributor.Value.Trim(), Role: contributor.Attribute(s_opfNamespace + "role")?.Value?.Trim())); + + foreach (XElement meta in metadata.Elements(s_opfNamespace + "meta")) + { + string? name = meta.Attribute("name")?.Value; + string? content = meta.Attribute("content")?.Value; + if (name is null || content is null) + continue; + + if (string.Equals(name, "calibre:series", StringComparison.OrdinalIgnoreCase)) + document.Series = content.Trim(); + else if (string.Equals(name, "calibre:series_index", StringComparison.OrdinalIgnoreCase)) + document.SeriesIndex = ParseDouble(content); + else if (string.Equals(name, "calibre:rating", StringComparison.OrdinalIgnoreCase)) + document.Rating = ParseInt(content); + } + + XElement? coverReference = xDocument.Root + ?.Element(s_opfNamespace + "guide") + ?.Elements(s_opfNamespace + "reference") + .FirstOrDefault(reference => string.Equals(reference.Attribute("type")?.Value, "cover", StringComparison.OrdinalIgnoreCase)); + document.CoverHref = coverReference?.Attribute("href")?.Value; + } + + /// + /// Gets the trimmed text of the child element with the specified of the element. + /// + /// The parent element. + /// The name of the child element. + /// The trimmed text, or when the element is missing or empty. + private static string? GetElementText(XElement parent, XName name) + { + string? value = parent.Element(name)?.Value; + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } + + /// + /// Parses a date string into a . + /// + /// The date string to parse. + /// The parsed date, or when the string is empty or cannot be parsed. + private static DateTimeOffset? ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + return DateTimeOffset.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTimeOffset result) ? result : null; + } + + /// + /// Parses a double string. + /// + /// The string to parse. + /// The parsed value, or when the string is empty or cannot be parsed. + private static double? ParseDouble(string value) + { + return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : null; + } + + /// + /// Parses an integer string. + /// + /// The string to parse. + /// The parsed value, or when the string is empty or cannot be parsed. + private static int? ParseInt(string value) + { + return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result) ? result : null; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj new file mode 100644 index 00000000..d8974eac --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj @@ -0,0 +1,32 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..c7bf9b3a --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")] diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index b526c7b5..dd02ed01 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -138,7 +138,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the volume or book number in the series, if applicable. /// - public int? VolumeNumber { get; set; } + public float? VolumeNumber { get; set; } // TODO: uncomment when series is implemented /// /// Gets or sets the series id, if the book is part of a series. @@ -190,6 +190,11 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// public string? AppleBooksId { get; set; } + /// + /// Gets or sets the file system path of the cover image of the book, if applicable. + /// + public string? CoverImagePath { get; set; } + /// /// Gets or sets the list of ISBN (International Standard Book Number) of the book. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs new file mode 100644 index 00000000..3bd58781 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Plugins; + +/// +/// Repository entity for the configuration of an artwork provider of a media library. +/// +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets or sets the Id of the configuration. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the media library the configuration belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the Id of the plugin providing the artwork. + /// + public required Guid PluginId { get; set; } + + /// + /// Gets or sets whether the artwork provider is enabled for the media library. + /// + public required bool IsEnabled { get; set; } + + /// + /// Gets or sets the rank of the artwork provider, determining the order in which providers are tried. + /// + public required int Rank { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs new file mode 100644 index 00000000..5f1ddb1f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Plugins; + +/// +/// Interface for the repository for the artwork provider configurations of media libraries. +/// +public interface IArtworkProviderConfigurationRepository : IRepository +{ + /// + /// Gets all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the artwork provider configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose artwork provider configuration is retrieved. + /// The Id of the plugin whose artwork provider configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken); + + /// + /// Inserts the provided into the storage medium, or updates it when it already exists. + /// + /// The artwork provider configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index 5fa6a3a7..ed2abbc8 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -110,14 +110,14 @@ public static class BookEntityMapping Optional bookFormat = Optional.FromNullable(repositoryEntity.Format); - return Book.Create( + Result bookResult = Book.Create( BookId.Create(repositoryEntity.Id), LibraryId.Create(repositoryEntity.LibraryId), repositoryEntity.Path, writtenContentMetadataResult.Value, bookFormat, Optional.FromNullable(repositoryEntity.Edition), - Optional.FromNullable(repositoryEntity.VolumeNumber), + Optional.FromNullable(repositoryEntity.VolumeNumber), Optional.None(), Optional.FromNullable(repositoryEntity.ASIN), Optional.FromNullable(repositoryEntity.GoodreadsId), @@ -133,6 +133,13 @@ public static class BookEntityMapping [.. isbnsResult.Select(isbn => isbn.Value)], [], [.. bookRatingsResult.Select(bookRating => bookRating.Value)]); + if (bookResult.IsFailure) + return bookResult.Errors; + + if (repositoryEntity.CoverImagePath is not null) + bookResult.Value.SetBookCoverImagePath(repositoryEntity.CoverImagePath); + + return bookResult; } /// @@ -217,7 +224,8 @@ public static class BookEntityMapping repositoryEntity.LastMetadataUpdateUtc, repositoryEntity.MetadataProvider, repositoryEntity.CreatedOnUtc, - repositoryEntity.UpdatedOnUtc + repositoryEntity.UpdatedOnUtc, + repositoryEntity.CoverImagePath ); } @@ -259,8 +267,7 @@ public static class BookEntityMapping repositoryEntity.Id, repositoryEntity.Title, repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear, - // TODO: populate from the book cover when cover support is implemented - null + repositoryEntity.CoverImagePath ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 1a61e61c..3ad75ac6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -56,6 +56,7 @@ public static class BookMapping GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null, BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, + CoverImagePath = domainEntity.CoverImagePath.HasValue ? domainEntity.CoverImagePath.Value : null, ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], MetadataStatus = domainEntity.MetadataStatus, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs index e295cd5b..59747d48 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; - +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; @@ -30,9 +29,9 @@ public static class BookMetadataDtoMapping public static Result ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc) { if (string.IsNullOrWhiteSpace(metadata.Title)) - return Lumina.Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; + return Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; if (metadata.ReleaseInfo is null) - return Lumina.Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; + return Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate), @@ -115,7 +114,7 @@ public static class BookMetadataDtoMapping writtenContentMetadataResult.Value, Optional.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null), Optional.FromNullable(metadata.Edition), - Optional.FromNullable(metadata.VolumeNumber), + Optional.FromNullable(metadata.VolumeNumber), Optional.None(), Optional.FromNullable(metadata.ASIN), Optional.FromNullable(metadata.GoodreadsId), @@ -132,6 +131,9 @@ public static class BookMetadataDtoMapping lastUpdateUtc ); + if (!string.IsNullOrWhiteSpace(metadata.CoverImagePath)) + book.SetBookCoverImagePath(metadata.CoverImagePath); + return Result.Success; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs index c3fa2f9f..1a7ca813 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -21,18 +21,19 @@ public static class GetBooksLiteRequestMapping { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) + { paginationData = new PaginationDataDto { CurrentPage = request.CurrentPage ?? 1, PerPage = request.PerPage ?? 200 }; - + } LibraryFilterDto libraryFilter = new() { LibraryId = request.LibraryId, SearchTerm = request.SearchTerm, FilterAlphaKey = request.FilterAlphaKey, - IgnoreThePrefixForAlphaPicker = request.IgnoreThePrefixForAlphaPicker + ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker }; return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..5dc3051b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryArtworkProvidersQuery ToQuery(this GetLibraryArtworkProvidersRequest request) + { + return new GetLibraryArtworkProvidersQuery(LibraryId: request.LibraryId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs new file mode 100644 index 00000000..d21150ff --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class LibraryArtworkProviderConfigurationEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The display name of the artwork provider. + /// The converted response. + public static LibraryArtworkProviderResponse ToResponse(this LibraryArtworkProviderConfigurationEntity configuration, string providerName) + { + return new LibraryArtworkProviderResponse( + PluginId: configuration.PluginId, + Name: providerName, + IsEnabled: configuration.IsEnabled, + Rank: configuration.Rank + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..7b0ab2fc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class ReorderLibraryArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request) + { + return new ReorderLibraryArtworkProvidersCommand( + LibraryId: request.LibraryId, + PluginIds: request.PluginIds + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs new file mode 100644 index 00000000..4494aeb8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class SetLibraryArtworkProviderEnabledRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request) + { + return new SetLibraryArtworkProviderEnabledCommand( + LibraryId: request.LibraryId, + PluginId: request.PluginId, + IsEnabled: request.IsEnabled + ); + } +} diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs index 2e14e2f2..c0c5d385 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -93,6 +93,33 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); } + /// + /// Defines a validation rule that ensures the float property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable float property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + /// /// Defines a validation rule that ensures the time span property is greater than the specified value. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs new file mode 100644 index 00000000..7967bf82 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path. +/// +public interface IBookArtworkService +{ + /// + /// Stores the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken); + + /// + /// Deletes the artwork of the book from the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An representing either a successful operation, or an error. + Result DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs index f75de677..0d0b29c9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -40,7 +40,7 @@ public record AddBookCommand( WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 78df6434..1e804b10 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -1,8 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -19,6 +20,8 @@ public class AddBookCommandValidator : AbstractValidator { RuleFor(command => command.LibraryId) .NotEmpty() + .WithError(Errors.WrittenContent.BookLibraryCannotBeNull) + .Must(id => id != Guid.Empty) .WithError(Errors.WrittenContent.BookLibraryCannotBeNull); RuleFor(command => command.Path) diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs new file mode 100644 index 00000000..a202a355 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Command for reordering the artwork providers of a media library. +/// +/// The Id of the media library whose artwork providers are reordered. +/// The plugin Ids in the new order, from highest to lowest rank. +public record ReorderLibraryArtworkProvidersCommand( + Guid LibraryId, + IReadOnlyList PluginIds +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs new file mode 100644 index 00000000..eff8b941 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Handler for the command to reorder the artwork providers of a media library. +/// +public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to reorder the artwork providers of a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can reorder the artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + + Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + for (int rank = 0; rank < command.PluginIds.Count; rank++) + { + Guid pluginId = command.PluginIds[rank]; + if (configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? configuration)) + { + configuration.Rank = rank + 1; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + } + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs new file mode 100644 index 00000000..770f3f31 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersCommandValidator() + { + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginIds) + .NotNull() + .WithError(Errors.Plugins.PluginIdsListCannotBeNull) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs new file mode 100644 index 00000000..e4acf111 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Command for enabling or disabling an artwork provider for a media library. +/// +/// The Id of the media library whose artwork provider is enabled or disabled. +/// The unique identifier of the plugin providing the artwork. +/// Whether the artwork provider should be enabled for the media library. +public record SetLibraryArtworkProviderEnabledCommand( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs new file mode 100644 index 00000000..c1974e81 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Handler for the command to enable or disable an artwork provider for a media library. +/// +public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to enable or disable an artwork provider for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(command); + if (validationResult.Count > 0) + return validationResult; + + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can configure the artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); + if (getConfigurationResult.IsFailure) + return getConfigurationResult.Errors; + + LibraryArtworkProviderConfigurationEntity configuration; + if (getConfigurationResult.Value is not null) + { + configuration = getConfigurationResult.Value; + configuration.IsEnabled = command.IsEnabled; + } + else + { + // compute the rank to assign to the new configuration, appending it after the existing ones + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + configuration = new LibraryArtworkProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = command.LibraryId, + PluginId = command.PluginId, + IsEnabled = command.IsEnabled, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + } + + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs new file mode 100644 index 00000000..040a486f --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Validates the needed validation rules for . +/// +public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledCommandValidator() + { + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs new file mode 100644 index 00000000..df65764d --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Query for getting the artwork providers configured for a media library. +/// +/// The Id of the media library whose artwork providers are retrieved. +public record GetLibraryArtworkProvidersQuery( + Guid LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs new file mode 100644 index 00000000..e5f518db --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Handler for the query to get the artwork providers configured for a media library. +/// +public class GetLibraryArtworkProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryArtworkProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the artwork providers configured for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryArtworkProvidersQuery query, CancellationToken cancellationToken) + { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can read the artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + + // build a plugin name lookup from the detected plugins + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + return getConfigurationsResult.Value + .OrderBy(configuration => configuration.Rank) + .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs new file mode 100644 index 00000000..4231fb1a --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryArtworkProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersQueryValidator() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs new file mode 100644 index 00000000..725576a6 --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Common; + +/// +/// Data transfer object for the artwork of a media item, provided by an artwork provider. +/// +/// The local file system path of the artwork, when the artwork is a local file. +/// The remote URL of the artwork, when the artwork is fetched over the web. +[DebuggerDisplay("LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")] +public sealed record ArtworkDto( + string? LocalPath, + string? RemoteUrl +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs index f557fe73..d0d5f723 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs @@ -36,7 +36,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; /// The list of ISBN (International Standard Book Number) of the book. /// The list of media contributors of the book. /// The list of ratings for the book. -/// The URL of the cover image of the book, if applicable. +/// The path of the cover image of the book, if applicable. public sealed record BookMetadataDto( string? Title, string? OriginalTitle, @@ -50,7 +50,7 @@ public sealed record BookMetadataDto( int? PageCount, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, @@ -64,5 +64,5 @@ public sealed record BookMetadataDto( List? Isbns, List? Contributors, List? Ratings, - string? CoverImageUrl + string? CoverImagePath ) : MetadataDto; diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs index d46fa0c9..7754e087 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -39,7 +39,7 @@ public record AddBookRequest( WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs index 6a5a1dc1..03b500ac 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -18,7 +18,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// Can be to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter, /// "#" to filter by titles whose first character is a digit, or "*" to filter by titles whose first character is neither a letter nor a digit. /// -/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. +/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// The name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. [DebuggerDisplay("LibraryId: {LibraryId}")] @@ -28,7 +28,7 @@ public record GetBooksLiteRequest( int? PerPage, string? SearchTerm, string? FilterAlphaKey, - bool IgnoreThePrefixForAlphaPicker, + bool ShouldIgnoreThePrefixForAlphaPicker, string? SortBy, SortOrder? SortOrder ); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs new file mode 100644 index 00000000..ff504590 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the artwork providers configured for a media library. +/// +/// The unique identifier of the media library whose artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record GetLibraryArtworkProvidersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs new file mode 100644 index 00000000..0e0f815c --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to reorder the artwork providers of a media library. +/// +/// The unique identifier of the media library whose artwork providers are reordered. Required. +/// The plugin Ids in the new order, from highest to lowest rank. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record ReorderLibraryArtworkProvidersRequest( + Guid LibraryId, + IReadOnlyList PluginIds +); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs new file mode 100644 index 00000000..bbfb2b95 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to enable or disable an artwork provider for a media library. +/// +/// The unique identifier of the media library whose artwork provider is enabled or disabled. Required. +/// The unique identifier of the plugin providing the artwork. Required. +/// Whether the artwork provider should be enabled for the media library. Required. +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public sealed record SetLibraryArtworkProviderEnabledRequest( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs index 483b7579..bf4ea18d 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -38,6 +38,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr /// The name of the plugin that enriched the metadata of the book, if applicable. /// The date and time when the book was created. /// The optional date and time when the book was updated. +/// The path of the cover image of the book, if available. [DebuggerDisplay("Title: {Metadata.Title}")] public record BookResponse( Guid Id, @@ -46,7 +47,7 @@ public record BookResponse( WrittenContentMetadataDto Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, @@ -64,5 +65,6 @@ public record BookResponse( DateTime? LastMetadataUpdateUtc, string? MetadataProvider, DateTime CreatedOnUtc, - DateTime? UpdatedOnUtc + DateTime? UpdatedOnUtc, + string? CoverPath ); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs new file mode 100644 index 00000000..c9b01c01 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents an artwork provider configured for a media library. +/// +/// The unique identifier of the plugin providing the artwork. +/// The display name of the artwork provider. +/// Whether the artwork provider is enabled for the media library. +/// The rank of the artwork provider, determining the order in which providers are tried. +public sealed record LibraryArtworkProviderResponse( + Guid PluginId, + string Name, + bool IsEnabled, + int Rank +); diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs new file mode 100644 index 00000000..89618882 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("LibraryArtworkProviderConfigurations"); + builder.HasKey(configuration => configuration.Id); + builder.Property(configuration => configuration.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + builder.Property(configuration => configuration.LibraryId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(configuration => configuration.PluginId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(configuration => configuration.IsEnabled) + .IsRequired() + .HasColumnOrder(3); + builder.Property(configuration => configuration.Rank) + .IsRequired() + .HasColumnOrder(4); + + // audit + builder.Property(configuration => configuration.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(configuration => configuration.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(configuration => configuration.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(configuration => configuration.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs new file mode 100644 index 00000000..f95ae4c2 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs @@ -0,0 +1,1358 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation")] + partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CoverImagePath") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs new file mode 100644 index 00000000..3c087310 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs @@ -0,0 +1,106 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "IgnoreThePrefixForAlphaPicker", + table: "UserSettings", + newName: "ShouldIgnoreThePrefixForAlphaPicker"); + + migrationBuilder.RenameColumn( + name: "DownloadMetadataFromWeb", + table: "Libraries", + newName: "CanDownloadMetadataFromWeb"); + + migrationBuilder.AddColumn( + name: "ShouldAggregateMetadataWhenMissing", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "VolumeNumber", + table: "Books", + type: "REAL", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true); + + migrationBuilder.AddColumn( + name: "CoverImagePath", + table: "Books", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateTable( + name: "LibraryArtworkProviderConfigurations", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + PluginId = table.Column(type: "TEXT", nullable: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false), + Rank = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_LibraryArtworkProviderConfigurations", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.DropColumn( + name: "ShouldAggregateMetadataWhenMissing", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "CoverImagePath", + table: "Books"); + + migrationBuilder.RenameColumn( + name: "ShouldIgnoreThePrefixForAlphaPicker", + table: "UserSettings", + newName: "IgnoreThePrefixForAlphaPicker"); + + migrationBuilder.RenameColumn( + name: "CanDownloadMetadataFromWeb", + table: "Libraries", + newName: "DownloadMetadataFromWeb"); + + migrationBuilder.AlterColumn( + name: "VolumeNumber", + table: "Books", + type: "INTEGER", + nullable: true, + oldClrType: typeof(float), + oldType: "REAL", + oldNullable: true); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 3bf74c6a..fbd03351 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -270,6 +270,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + b.Property("CoverImage") .HasMaxLength(255) .HasColumnType("TEXT") @@ -283,12 +289,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(9); - b.Property("DownloadMetadataFromWeb") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER") - .HasDefaultValue(true) - .HasColumnOrder(6); - b.Property("IsEnabled") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") @@ -535,6 +535,9 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(28); + b.Property("CoverImagePath") + .HasColumnType("TEXT"); + b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(33); @@ -685,8 +688,8 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(34); - b.Property("VolumeNumber") - .HasColumnType("INTEGER") + b.Property("VolumeNumber") + .HasColumnType("REAL") .HasColumnOrder(20); b.HasKey("Id"); @@ -698,6 +701,51 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Books", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => { b.Property("Id") @@ -964,10 +1012,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(5); - b.Property("IgnoreThePrefixForAlphaPicker") - .HasColumnType("INTEGER") - .HasColumnOrder(4); - b.Property("IsPaginationEnabled") .HasColumnType("INTEGER") .HasColumnOrder(2); @@ -980,6 +1024,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(3); + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs new file mode 100644 index 00000000..f3e0fc6c --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Plugins; + +/// +/// Repository for the artwork provider configurations of media libraries. +/// +internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderConfigurationRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ArtworkProviderConfigurationRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryArtworkProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the artwork provider configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose artwork provider configuration is retrieved. + /// The Id of the plugin whose artwork provider configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + public async Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Inserts an artwork provider configuration into the storage medium, or updates it when it already exists. + /// + /// The artwork provider configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken) + { + LibraryArtworkProviderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false); + if (existingConfiguration is null) + _luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration); + else + { + // update only the mutable fields, preserving the Id of the existing configuration + existingConfiguration.LibraryId = configuration.LibraryId; + existingConfiguration.PluginId = configuration.PluginId; + existingConfiguration.IsEnabled = configuration.IsEnabled; + existingConfiguration.Rank = configuration.Rank; + } + return Result.Updated; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs index bab30199..a007e820 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs @@ -29,4 +29,9 @@ public enum BookRatingSource /// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text. /// GoogleBooks, + + /// + /// Ratings sourced from Calibre, an ebook management application. + /// + Calibre, } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index c6b1a436..5fc666a9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -66,7 +66,7 @@ public sealed class Book : AggregateRoot /// /// Gets the volume or book number in the series, if applicable. /// - public Optional VolumeNumber { get; private set; } + public Optional VolumeNumber { get; private set; } /// /// Gets the series name, if the book is part of a series. @@ -118,6 +118,11 @@ public sealed class Book : AggregateRoot /// public Optional AppleBooksId { get; private set; } + /// + /// Gets the file system path of the cover image of the book, if applicable. + /// + public Optional CoverImagePath { get; private set; } + /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// @@ -165,7 +170,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -202,6 +207,7 @@ public sealed class Book : AggregateRoot GoogleBooksId = googleBooksId; BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; + CoverImagePath = Optional.None(); CreatedOnUtc = createdOnUtc; UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; _isbns = isbns; @@ -240,7 +246,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -317,7 +323,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -381,6 +387,15 @@ public sealed class Book : AggregateRoot MetadataStatus = MetadataStatus.Failed; } + /// + /// Sets the file system path of the cover image of the book. + /// + /// The file system path of the cover image of the book. + public void SetBookCoverImagePath(string coverImagePath) + { + CoverImagePath = coverImagePath; + } + /// /// Applies the enriched and the related fields to the book, marking its metadata as enriched by the provided . /// @@ -406,7 +421,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index 28805417..1b0e72f1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -33,9 +33,8 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner /// Creates the media library scan jobs for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// Whether the library permits downloading data from the web, or not. /// A collection of media library scan jobs. - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb) + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId) { // declare the list of jobs that this scanner requires IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); @@ -53,14 +52,12 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob); mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob); - // when the library permits downloading data from the web, the metadata enrichment job is the last job in the directed acyclic job graph, - // running after the scan results save job, so that the books are materialized before their metadata is enriched - if (downloadMetadataFromWeb) - { - IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); - mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); - mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob); - } + // the metadata enrichment job is always the last job in the directed acyclic job graph, running after the scan results save job, + // so that the books are materialized before their metadata is enriched. The job itself is the host-side gate that skips the providers + // requiring access to the web when the media library does not permit downloading data from the web, so that the local providers still run offline + IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); + mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); + mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob); // return the top level jobs that will be triggered when the scan will be started yield return fileSystemDiscoveryJob; diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 16ca5a37..a9c05cd1 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -11,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; @@ -28,6 +29,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Infrastructure.Core.Plugins; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Themes; @@ -102,6 +104,10 @@ public static class InfrastructureLayerServices services.AddSingleton(); + // book artwork: stores the artwork of the books into the internal media directory + services.AddHttpClient(); + services.AddScoped(); + // plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins"; string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs new file mode 100644 index 00000000..39080b78 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs @@ -0,0 +1,337 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Stores the artwork of a book into the internal media directory, under a per-book directory, and returns its relative path. +/// +internal sealed class BookArtworkService : IBookArtworkService +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _environmentContext; + private readonly IPathService _pathService; + private readonly IHttpClientFactory _httpClientFactory; + private readonly MediaSettingsDto _mediaSettings; + + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected service for handling file system paths. + /// Injected factory used to create the HTTP clients that download the remote artwork. + /// Injected service for retrieving . + public BookArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions mediaSettingsOptions) + { + _environmentContext = environmentContext; + _pathService = pathService; + _httpClientFactory = httpClientFactory; + _mediaSettings = mediaSettingsOptions.Value; + } + + /// + /// Stores the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken) + { + // resolve the local file path of the artwork, downloading it to a temporary file when it is remote + Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false); + if (resolveSourceResult.IsFailure) + return resolveSourceResult.Errors; + string sourcePath = resolveSourceResult.Value.Path; + + try + { + Result storeResult = await StoreArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, sourcePath, cancellationToken).ConfigureAwait(false); + if (storeResult.IsFailure) + return storeResult.Errors; + return storeResult; + } + finally + { + // remove the temporary file downloaded for the remote artwork, never a local file of the user + if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath)) + { + try + { + File.Delete(sourcePath); + } + catch (IOException) + { + // a failed cleanup of the temporary file must not mask the result of the operation + } + catch (UnauthorizedAccessException) + { + // a failed cleanup of the temporary file must not mask the result of the operation + } + } + } + } + + /// + /// Deletes the artwork of the book from the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An representing either a successful operation, or an error. + public Result DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + Result artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + DeleteCover(artworkDirectoryPathResult.Value); + return Result.Deleted; + } + + /// + /// Stores the artwork file at into the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The file system path of the artwork file to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> StoreArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, string sourcePath, CancellationToken cancellationToken) + { + Result sourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (sourcePathIdResult.IsFailure) + return sourcePathIdResult.Errors; + + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value); + if (fileExistsResult.IsFailure) + return fileExistsResult.Errors; + if (!fileExistsResult.Value) + return Errors.FileSystemManagement.FileNotFound; + + // reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine + if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint)) + return Errors.FileSystemManagement.InvalidPath; + + // reject the artwork when it exceeds the maximum allowed size + FileInfo sourceFileInfo = new(sourcePath); + if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + + // make sure the file is an actual supported image + Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageTypeResult.IsFailure) + return imageTypeResult.Errors; + if (imageTypeResult.Value == ImageType.None) + return Errors.Library.CoverFileMustBeAnImage; + + Result artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + + Result ensureDirectoryResult = EnsureDirectory(artworkDirectoryPathResult.Value); + if (ensureDirectoryResult.IsFailure) + return ensureDirectoryResult.Errors; + + // delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind + DeleteCover(artworkDirectoryPathResult.Value); + + Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPathResult.Value); + if (artworkDirectoryPathIdResult.IsFailure) + return artworkDirectoryPathIdResult.Errors; + + // copy the artwork file from the source location + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true); + if (copyFileResult.IsFailure) + return copyFileResult.Errors; + + // rename the copied file to the standard naming + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}"); + if (renameFileResult.IsFailure) + return renameFileResult.Errors; + + // get the internal relative path for the copied file + string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; + if (!relativePath.StartsWith(_pathService.PathSeparator)) + relativePath = $"{_pathService.PathSeparator}{relativePath}"; + return relativePath; + } + + /// + /// Resolves the local file system path of the , downloading it to a temporary file when it is remote. + /// + /// The artwork whose source path is resolved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resolved local source of the artwork, or an error. + private async Task> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken) + { + if (!string.IsNullOrWhiteSpace(artwork.LocalPath)) + return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: false); + + if (string.IsNullOrWhiteSpace(artwork.RemoteUrl)) + return Errors.FileSystemManagement.FileNotFound; + + // download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size + using HttpClient httpClient = _httpClientFactory.CreateClient(); + string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); + bool downloaded = false; + try + { + using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + return Errors.FileSystemManagement.FileNotFound; + + await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true); + + byte[] buffer = new byte[81920]; + long totalRead = 0; + int bytesRead; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + totalRead += bytesRead; + if (totalRead > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + downloaded = true; + return new ArtworkSourceResult(tempPath, IsTemporary: true); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return Errors.FileSystemManagement.FileNotFound; + } + finally + { + // remove the partially downloaded temporary file when the download failed + if (!downloaded && File.Exists(tempPath)) + File.Delete(tempPath); + } + } + + /// + /// Builds the file system path of the directory of the book artwork, under the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An containing either the file system path of the book artwork directory, or an error. + private Result BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + Result mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory); + if (mediaRootPathResult.IsFailure) + return mediaRootPathResult.Errors; + Result booksPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.BooksDirectory); + if (booksPathResult.IsFailure) + return booksPathResult.Errors; + + Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + if (librarySegmentResult.IsFailure) + return librarySegmentResult.Errors; + Result authorSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(authorName) ? "Unknown" : authorName); + if (authorSegmentResult.IsFailure) + return authorSegmentResult.Errors; + Result bookSegmentResult = _pathService.SanitizeSegment($"{bookTitle}-{bookId}"); + if (bookSegmentResult.IsFailure) + return bookSegmentResult.Errors; + + Result libraryPathResult = _pathService.CombinePath(booksPathResult.Value, librarySegmentResult.Value.Name); + if (libraryPathResult.IsFailure) + return libraryPathResult.Errors; + Result authorPathResult = _pathService.CombinePath(libraryPathResult.Value, authorSegmentResult.Value.Name); + if (authorPathResult.IsFailure) + return authorPathResult.Errors; + return _pathService.CombinePath(authorPathResult.Value, bookSegmentResult.Value.Name); + } + + /// + /// Creates the directory at , along with its missing parents. + /// + /// The file system path of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(string directoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(directoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (directoryExistsResult.Value) + return Result.Success; + + string? parentDirectoryPath = Path.GetDirectoryName(directoryPath); + if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal)) + { + Result createParentResult = EnsureDirectory(parentDirectoryPath); + if (createParentResult.IsFailure) + return createParentResult.Errors; + } + + Result parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath); + if (parentDirectoryPathIdResult.IsFailure) + return parentDirectoryPathIdResult.Errors; + + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath)); + if (createDirectoryResult.IsFailure) + return createDirectoryResult.Errors; + return Result.Success; + } + + /// + /// Deletes the cover files of the book from the . + /// + /// The file system path of the directory of the book artwork. + private void DeleteCover(string artworkDirectoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (directoryPathIdResult.IsFailure) + return; + + Result> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true); + if (getFilesResult.IsFailure) + return; + + foreach (FileSystemPathId filePathId in getFilesResult.Value) + if (Regex.IsMatch(filePathId.Path, @"[\\/]cover\.[^.\\/]+$", RegexOptions.IgnoreCase)) + _environmentContext.FileProviderService.DeleteFile(filePathId); + } + + /// + /// Describes the resolved local source of the artwork. + /// + private sealed record ArtworkSourceResult(string Path, bool IsTemporary); +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 281327e4..1220a724 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -25,6 +25,7 @@ + diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs new file mode 100644 index 00000000..09b9250c --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.Core.Metadata; + +/// +/// Contract for a plugin that provides artwork for media items (i.e., covers, banners, fanart, etc). +/// +public interface IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + string Name { get; } + + /// + /// Gets the media library types this artwork provider supports. + /// + IReadOnlyList SupportedLibraryTypes { get; } + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + bool RequiresWebAccess { get; } + + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found. + Task GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs new file mode 100644 index 00000000..ea296737 --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.Core.Metadata; + +/// +/// Contract for a plugin that provides artwork for media items, typed to the media item lookup type. +/// +/// The type of the lookup describing the media item. +public interface IArtworkProvider : IArtworkProvider + where TLookup : MetadataLookupDto +{ + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found. + Task GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); + + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found or the lookup is of another runtime type. + async Task IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + { + return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; + } +} diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 920f999a..a854cc7c 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -171,7 +171,14 @@ public static class PresentationApiLayerServices services.AddAuthorization(); - services.AddFastEndpoints(endpointDiscoveryOptions => endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]); + services.AddFastEndpoints(endpointDiscoveryOptions => + { + endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]; + // only scan the application assembly, so that duplicate copies of it loaded into other assembly load + // contexts during the process lifetime are never scanned again; otherwise a single host can register + // every endpoint multiple times and fail with duplicate routes + endpointDiscoveryOptions.DisableAutoDiscovery = true; + }); services.AddOpenApi(); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index d10992bb..50657a81 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -25,5 +25,8 @@ public static partial class ApiRoutes public const string GET_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers"; public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "/libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers/reorder"; + public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; + public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; + public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs index 0c45d1bd..197d0cc7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System.Diagnostics.CodeAnalysis; -using System.Collections.Generic; -using Lumina.Contracts.DTO.Common; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.DTO.MediaContributors; using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; @@ -284,7 +284,8 @@ public class AddLibraryEndpointSummary : Summary r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required."); RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..8aff60f8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers route. +/// +public class GetLibraryArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryArtworkProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library artwork providers queries. + public GetLibraryArtworkProvidersEndpoint(IQueryHandler>> getLibraryArtworkProvidersQueryHandler) + { + _getLibraryArtworkProvidersQueryHandler = getLibraryArtworkProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the artwork providers configured for the media library identified by . + /// + /// The request containing the Id of the media library whose artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryArtworkProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..d8618092 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers configured for a media library."; + Description = "Retrieves the artwork providers configured for a media library, with their enabled state and rank."; + + ExampleRequest = new GetLibraryArtworkProvidersRequest( + LibraryId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork."); + ResponseParam(r => r.Name, "The display name of the artwork provider."); + ResponseParam(r => r.IsEnabled, "Whether the artwork provider is enabled for the media library."); + ResponseParam(r => r.Rank, "The rank of the artwork provider, determining the order in which providers are tried."); + + Response(200, "The artwork providers configured for the media library are returned.", + example: new LibraryArtworkProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Calibre", + IsEnabled: true, + Rank: 1 + ), + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + Rank: 2 + ) + } + ); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + } + } + ); + + 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 + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..57e492af --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers/reorder route. +/// +public class ReorderLibraryArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _reorderLibraryArtworkProvidersCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling reorder library artwork providers commands. + public ReorderLibraryArtworkProvidersEndpoint(ICommandHandler> reorderLibraryArtworkProvidersCommandHandler) + { + _reorderLibraryArtworkProvidersCommandHandler = reorderLibraryArtworkProvidersCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reorders the artwork providers of the media library identified by . + /// + /// The request containing the Id of the media library and the plugin Ids in the new order. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result result = await _reorderLibraryArtworkProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..4089dcd1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersEndpointSummary() + { + Summary = "Reorders the artwork providers of a media library."; + Description = "Reorders the artwork providers of a media library, determining the order in which the providers are tried during the artwork enrichment of the library scans."; + + ExampleRequest = new ReorderLibraryArtworkProvidersRequest( + LibraryId: Guid.NewGuid(), + PluginIds: + [ + Guid.NewGuid(), + Guid.NewGuid() + ] + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); + RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); + + Response(200, "The artwork providers of the media library were successfully reordered."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + } + } + ); + + 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 + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdsListCannotBeNull", + "PluginIdsListCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs new file mode 100644 index 00000000..b525dac5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. +/// +public class SetLibraryArtworkProviderEnabledEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _setLibraryArtworkProviderEnabledCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling set library artwork provider enabled commands. + public SetLibraryArtworkProviderEnabledEndpoint(ICommandHandler> setLibraryArtworkProviderEnabledCommandHandler) + { + _setLibraryArtworkProviderEnabledCommandHandler = setLibraryArtworkProviderEnabledCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Enables or disables the artwork provider identified by for the media library. + /// + /// The request containing the Ids of the media library and of the artwork provider. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) + { + Result result = await _setLibraryArtworkProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs new file mode 100644 index 00000000..0d9a6088 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledEndpointSummary() + { + Summary = "Enables or disables an artwork provider for a media library."; + Description = "Enables or disables the artwork provider for the media library, so that it is included or excluded from the artwork enrichment of the library scans."; + + ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( + LibraryId: Guid.NewGuid(), + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); + RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library. Required."); + + Response(200, "The artwork provider was successfully enabled or disabled for the media library."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + } + } + ); + + 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 + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 41052581..2e7a659f 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -166,7 +166,13 @@ public class Program app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(mediaRootPath), - RequestPath = "/media" + RequestPath = "/media", + OnPrepareResponse = staticFileContext => + { + // the served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin + staticFileContext.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; + staticFileContext.Context.Response.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:"; + } }); app.MapHub("/scanProgressHub"); diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs index b746cff9..3159edd1 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs @@ -137,7 +137,7 @@ public class BookDto /// /// Gets the volume or book number in the series, if applicable. /// - public int? VolumeNumber { get; init; } + public float? VolumeNumber { get; init; } /// /// Gets the series id, if the book is part of a series. diff --git a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs index a72eb429..11beb9f6 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs @@ -29,4 +29,9 @@ public enum BookRatingSource /// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text. /// GoogleBooks, + + /// + /// Ratings sourced from Calibre, an ebook management application. + /// + Calibre, } diff --git a/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs index d6ccbcd7..ea5c1b47 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs @@ -42,7 +42,7 @@ public class GetBooksLiteRequest /// /// Gets or sets whether the leading "The " prefix of a title is ignored when computing the alpha key, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets the name of the field by which to sort the results. diff --git a/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs index d0fb3591..f444023c 100644 --- a/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs @@ -93,6 +93,33 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); } + /// + /// Defines a validation rule that ensures the float property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable float property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + /// /// Defines a validation rule that ensures the time span property is greater than the specified value. /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs index c8c344d4..e411d87b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Text; @@ -71,7 +70,7 @@ public class GetLibraryItemsEndpoint : BaseEndpoint r.PerPage, "Optional. The maximum number of books to retrieve per page."); RequestParam(r => r.SearchTerm, "Optional. The search term used to filter results."); RequestParam(r => r.FilterAlphaKey, "Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); RequestParam(r => r.SortBy, "Optional. The name of the field by which to sort the results."); RequestParam(r => r.SortOrder, "Optional. The direction in which to sort the results."); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index 6832ccf2..c6fd0f68 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -100,7 +100,7 @@ params.set('searchTerm', state.searchTerm); if (state.alphaKey !== null) params.set('filterAlphaKey', state.alphaKey); - params.set('ignoreThePrefixForAlphaPicker', state.ignoreThePrefix); + params.set('shouldIgnoreThePrefixForAlphaPicker', state.ignoreThePrefix); params.set('sortOrder', state.sortOrder); return `${url}?${params.toString()}`; } @@ -259,7 +259,7 @@ async function loadSettingsAsync() { const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)'); if (data) { - state.ignoreThePrefix = data.ignoreThePrefixForAlphaPicker === true; + state.ignoreThePrefix = data.shouldIgnoreThePrefixForAlphaPicker === true; state.perPage = data.isPaginationEnabled === true ? data.itemsPerPage : null; } } diff --git a/src/Lumina.sln b/src/Lumina.sln index 678d100f..6b83d501 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -208,6 +208,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{02EA EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary", "..\plugins\Lumina.Plugins.OpenLibrary\Lumina.Plugins.OpenLibrary.csproj", "{EADCD78B-04D5-4FE3-855C-E3015531EC8E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre", "..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj", "{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Domain.SharedKernel", "Lumina.Domain.SharedKernel\Lumina.Domain.SharedKernel.csproj", "{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}" @@ -244,6 +246,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary.Fixtures", "..\tests\Common\Lumina.Plugins.OpenLibrary.Fixtures\Lumina.Plugins.OpenLibrary.Fixtures.csproj", "{16F65859-93AB-499F-A0BE-9EC05E20435F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.UnitTests", "..\tests\UnitTests\Lumina.Plugins.Calibre.UnitTests\Lumina.Plugins.Calibre.UnitTests.csproj", "{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.Fixtures", "..\tests\Common\Lumina.Plugins.Calibre.Fixtures\Lumina.Plugins.Calibre.Fixtures.csproj", "{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{2872042D-061F-4C76-8017-0A518A7E28A7}" @@ -461,6 +467,18 @@ Global {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x64.Build.0 = Release|Any CPU {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.ActiveCfg = Release|Any CPU {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.Build.0 = Release|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -665,6 +683,30 @@ Global {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x64.Build.0 = Release|Any CPU {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.ActiveCfg = Release|Any CPU {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.Build.0 = Release|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -722,6 +764,7 @@ Global {788FADE4-342D-4919-8E5C-10CA8EDBE954} = {70B56088-6D3A-481E-9459-79AC6B16FEC1} {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {EADCD78B-04D5-4FE3-855C-E3015531EC8E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {9450EAC6-1F33-4BE1-89E3-0275885FE3EE} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {E6449D94-C33A-41CE-9047-7298CF20C311} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} @@ -740,6 +783,8 @@ Global {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {FEC00EBD-6A64-4280-B0F7-1EC5321C294A} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {16F65859-93AB-499F-A0BE-9EC05E20435F} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {2872042D-061F-4C76-8017-0A518A7E28A7} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} EndGlobalSection diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs new file mode 100644 index 00000000..657a2a25 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryArtworkProviderConfigurationEntityFixture +{ + /// + /// Creates a random valid for the provided media library, plugin and rank. + /// + /// The Id of the media library the configuration belongs to. + /// The Id of the plugin providing the artwork. + /// The rank of the artwork provider, determining the order in which providers are tried. + /// Whether the artwork provider is enabled or not. + /// The created . + public LibraryArtworkProviderConfigurationEntity Create( + Guid libraryId, + Guid pluginId, + int rank, + bool isEnabled = true) + { + return new Faker() + .RuleFor(configuration => configuration.Id, faker => faker.Random.Guid()) + .RuleFor(configuration => configuration.LibraryId, libraryId) + .RuleFor(configuration => configuration.PluginId, pluginId) + .RuleFor(configuration => configuration.IsEnabled, isEnabled) + .RuleFor(configuration => configuration.Rank, rank) + .RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past()) + .RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid()) + .RuleFor(configuration => configuration.UpdatedOnUtc, faker => faker.Date.Recent()) + .RuleFor(configuration => configuration.UpdatedBy, faker => faker.Random.Guid()) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// The Id of the media library the configurations belong to. + /// The Id of the plugin providing the artwork. + /// The rank of the artwork providers. + /// List of configured instances. + public List CreateMany(int count, Guid libraryId, Guid pluginId, int rank) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(libraryId, pluginId, rank))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs new file mode 100644 index 00000000..42ecdbc6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandFixture +{ + /// + /// Creates a random valid command to reorder the artwork providers of a media library. + /// + /// Optional. The Id of the media library whose artwork providers are reordered. + /// Optional. The plugin Ids in the new order. + /// The created command. + public ReorderLibraryArtworkProvidersCommand Create( + Guid? libraryId = null, + IReadOnlyList? pluginIds = null) + { + return new Faker() + .CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand( + default, + default!)) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) + .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs new file mode 100644 index 00000000..db917fec --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandFixture +{ + /// + /// Creates a random valid command to enable or disable an artwork provider for a media library. + /// + /// Optional. The Id of the media library whose artwork provider is enabled or disabled. + /// Optional. The Id of the plugin providing the artwork. + /// Whether the artwork provider should be enabled for the media library. + /// The created command. + public SetLibraryArtworkProviderEnabledCommand Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool isEnabled = true) + { + return new Faker() + .CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand( + default, + default, + true)) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) + .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) + .RuleFor(x => x.IsEnabled, isEnabled) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs new file mode 100644 index 00000000..8f1678e3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryFixture +{ + /// + /// Creates a random valid query to get the artwork providers of a media library. + /// + /// Optional. The Id of the media library whose artwork providers are retrieved. + /// The created query. + public GetLibraryArtworkProvidersQuery Create( + Guid? libraryId = null) + { + return new Faker() + .CustomInstantiator(f => new GetLibraryArtworkProvidersQuery( + libraryId ?? Guid.NewGuid())) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs new file mode 100644 index 00000000..54f61ead --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtworkDtoFixture +{ + /// + /// Creates an . + /// + /// Optional. The local file system path of the artwork. + /// Optional. The remote URL of the artwork. + /// The created . + public ArtworkDto Create( + string? localPath = null, + string? remoteUrl = null) + { + return new ArtworkDto(localPath, remoteUrl); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..d6b93aca --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork providers are retrieved. + /// The created . + public GetLibraryArtworkProvidersRequest Create( + Guid? libraryId = null) + { + return new GetLibraryArtworkProvidersRequest( + libraryId ?? _faker.Random.Guid() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..8c65fa86 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork providers are reordered. + /// Optional. The plugin Ids in the new order. + /// The created . + public ReorderLibraryArtworkProvidersRequest Create( + Guid? libraryId = null, + IReadOnlyList? pluginIds = null) + { + return new ReorderLibraryArtworkProvidersRequest( + libraryId ?? _faker.Random.Guid(), + pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs new file mode 100644 index 00000000..cd7f3dbb --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork provider is enabled or disabled. + /// Optional. The Id of the plugin providing the artwork. + /// Optional. Whether the artwork provider should be enabled. + /// The created . + public SetLibraryArtworkProviderEnabledRequest Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool? isEnabled = null) + { + return new SetLibraryArtworkProviderEnabledRequest( + libraryId ?? _faker.Random.Guid(), + pluginId ?? _faker.Random.Guid(), + isEnabled ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs new file mode 100644 index 00000000..dc52ae02 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryArtworkProviderResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the artwork. + /// Optional. The display name of the artwork provider. + /// Optional. Whether the artwork provider is enabled for the media library. + /// Optional. The rank of the artwork provider. + /// The created . + public LibraryArtworkProviderResponse Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryArtworkProviderResponse( + pluginId ?? Guid.NewGuid(), + name ?? _faker.Company.CompanyName(), + isEnabled ?? _faker.Random.Bool(), + rank ?? _faker.Random.Int(1, 100)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs new file mode 100644 index 00000000..fc701d23 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Setup; + +/// +/// test double that returns the configured response for every request, without performing any network I/O. +/// +[ExcludeFromCodeCoverage] +internal sealed class StubHttpMessageHandler : HttpMessageHandler +{ + private HttpStatusCode _statusCode; + private byte[] _responseBody; + + /// + /// Initializes a new instance of the class. + /// + /// The initial status code of the response to return. + /// The initial body of the response to return. + public StubHttpMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK, byte[]? responseBody = null) + { + _statusCode = statusCode; + _responseBody = responseBody ?? []; + } + + /// + /// Configures the response to return for every subsequent request. + /// + /// The status code of the response to return. + /// The body of the response to return. + public void SetResponse(HttpStatusCode statusCode, byte[] responseBody) + { + _statusCode = statusCode; + _responseBody = responseBody; + } + + /// + /// Returns a response with the configured status code and body. + /// + /// The request, which is ignored. + /// Cancellation token that can be used to cancel the operation. + /// The configured response. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(new HttpResponseMessage(_statusCode) + { + Content = new ByteArrayContent(_responseBody) + }); + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs new file mode 100644 index 00000000..c4fac999 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfContributorDtoFixture +{ + /// + /// Creates an . + /// + /// The name of the contributor. + /// The role code of the contributor, for example bkp for the book producer. + /// The created . + public OpfContributorDto Create( + string name = "Test Contributor", + string? role = null) + { + return new OpfContributorDto(name, role); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs new file mode 100644 index 00000000..2306d084 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfCreatorDtoFixture +{ + /// + /// Creates an . + /// + /// The name of the creator. + /// The role code of the creator, for example aut for author. + /// The created . + public OpfCreatorDto Create( + string name = "Test Creator", + string? role = null) + { + return new OpfCreatorDto(name, role); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs new file mode 100644 index 00000000..e706f2dd --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfDocumentDtoFixture +{ + /// + /// Creates an . + /// + /// Optional. The title of the book. + /// Optional. The description of the book, in HTML format. + /// Optional. The publisher of the book. + /// Optional. The publication date of the book. + /// Optional. The language code of the book. + /// Optional. The name of the series the book belongs to. + /// Optional. The index of the book within its series. + /// Optional. The personal rating of the book, on a scale of 0 to 10. + /// Optional. The href of the cover image, relative to the directory of the book. + /// Optional. The subjects of the book, used as tags. + /// Optional. The creators of the book. + /// Optional. The contributors of the book. + /// Optional. The identifiers of the book, with their schemes. + /// The created . + public OpfDocumentDto Create( + string? title = null, + string? description = null, + string? publisher = null, + DateTimeOffset? publishDate = null, + string? languageCode = null, + string? series = null, + double? seriesIndex = null, + int? rating = null, + string? coverHref = null, + IEnumerable? subjects = null, + IEnumerable? creators = null, + IEnumerable? contributors = null, + IEnumerable? identifiers = null) + { + OpfDocumentDto document = new() + { + Title = title, + Description = description, + Publisher = publisher, + PublishDate = publishDate, + LanguageCode = languageCode, + Series = series, + SeriesIndex = seriesIndex, + Rating = rating, + CoverHref = coverHref + }; + if (subjects is not null) + document.Subjects.AddRange(subjects); + if (creators is not null) + document.Creators.AddRange(creators); + if (contributors is not null) + document.Contributors.AddRange(contributors); + if (identifiers is not null) + document.Identifiers.AddRange(identifiers); + return document; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs new file mode 100644 index 00000000..0b58df76 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfIdentifierDtoFixture +{ + /// + /// Creates an . + /// + /// The scheme of the identifier, for example ISBN or GOODREADS. + /// The value of the identifier. + /// The created . + public OpfIdentifierDto Create( + string scheme = "ISBN", + string value = "9780306406157") + { + return new OpfIdentifierDto(scheme, value); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs new file mode 100644 index 00000000..ac5f3324 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata; + +/// +/// Concrete used to represent a lookup that is not a book lookup. +/// +[ExcludeFromCodeCoverage] +internal sealed record TestMetadataLookup(Guid LibraryId, string Path) : MetadataLookupDto; diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs new file mode 100644 index 00000000..e8a90623 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class TestMetadataLookupFixture +{ + /// + /// Creates a that is not a book lookup. + /// + /// The Id of the media library, or to generate a random one. + /// The file system path of the media item. + /// The created . + public TestMetadataLookup Create( + Guid? libraryId = null, + string? path = null) + { + return new TestMetadataLookup(libraryId ?? Guid.NewGuid(), path ?? "/some/path"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj new file mode 100644 index 00000000..bacaf455 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..59eb394e --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.Calibre.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.Calibre.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..7d78014b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +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.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? providers = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(providers); + Assert.Equal(2, providers!.Count); + Assert.Equal(pluginIdA, providers[0].PluginId); + Assert.Equal(1, providers[0].Rank); + Assert.Equal(pluginIdB, providers[1].PluginId); + Assert.Equal(2, providers[1].Rank); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? providers = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(providers); + Assert.Empty(providers!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds two instances in the database. + /// + /// The Id of the media library. + /// The Id of the first plugin. + /// The Id of the second plugin. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true)); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..6887dc59 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); + await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( + libraryId: libraryId, + pluginIds: [pluginIdB, pluginIdA] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List configurations = await dbContext.LibraryArtworkProviderConfigurations + .Where(config => config.LibraryId == libraryId) + .OrderBy(config => config.Rank) + .ToListAsync(); + Assert.Equal(2, configurations.Count); + Assert.Equal(pluginIdB, configurations[0].PluginId); + Assert.Equal(1, configurations[0].Rank); + Assert.Equal(pluginIdA, configurations[1].PluginId); + Assert.Equal(2, configurations[1].Rank); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the media library. + /// The Id of the plugin. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..a8d33410 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginId = Guid.NewGuid(); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + Assert.Equal(1, configuration.Rank); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginId = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the media library. + /// The Id of the plugin. + /// Whether the provider is enabled. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..4e6d5c9f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers route. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers", 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 injection + public async Task GetLibraryArtworkProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library with an artwork provider configuration, so a valid id would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artwork-providers"); + + // Assert + // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding + // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) + // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..9749c528 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers/reorder route. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( + libraryId: Guid.NewGuid(), + pluginIds: [Guid.NewGuid()] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Plugins--")] // destructive injection + public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) + { + // Arrange + // authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId, rank: 1); + await SeedConfigurationAsync(libraryId, rank: 2); + + // Act + // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization + // before it ever reaches the endpoint handler + HttpResponseMessage response = await client.PutAsJsonAsync( + $"/api/v1/libraries/{libraryId}/artwork-providers/reorder", + new { libraryId, pluginIds = new[] { maliciousPluginId } }); + + // Assert + // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and + // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 + // (pre-existing production bug, not fixed here) + // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..72501673 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string pluginId = Guid.NewGuid().ToString(); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", 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 injection + public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + // authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request); + + // Assert + // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding + // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) + // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs new file mode 100644 index 00000000..05c0dbf8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -0,0 +1,236 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork; + +/// +/// Contains security tests for the contract, exercised through the real implementation resolved from the dependency injection container. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkServiceSecurityTests +{ + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IBookArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookArtworkServiceSecurityTests() + { + IEnvironmentContext mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); + + IConfiguration mockConfiguration = Substitute.For(); + mockConfiguration.GetSection(Arg.Any()).Returns(Substitute.For()); + + ServiceCollection services = new(); + services.AddInfrastructureLayerServices(mockConfiguration); + services.AddScoped(_ => mockEnvironmentContext); + // the real path service is used, so that the sanitization of hostile segment names is exercised + services.AddScoped(_ => CreateRealPathService()); + services.AddSingleton(Options.Create(mediaSettings)); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using IServiceScope scope = serviceProvider.CreateScope(); + _sut = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // the environment does not support creating reparse points + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenNameSegmentsContainPathTraversal_ShouldSanitizeThemIntoLiteralSegments() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[1024]); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + + string capturedDestinationPath = string.Empty; + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Do(destination => capturedDestinationPath = destination.Path), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg")))); + + // Act + Result result = await _sut.SaveBookArtworkAsync( + Guid.NewGuid(), + Guid.NewGuid(), + libraryName: "..\\..\\Library", + authorName: "..\\evil", + bookTitle: "..\\..\\cover", + _artworkDtoFixture.Create(localPath: sourcePath), + CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.False(string.IsNullOrEmpty(capturedDestinationPath)); + string[] segments = capturedDestinationPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries); + Assert.DoesNotContain(segments, segment => segment == ".."); + Assert.DoesNotContain(segments, segment => segment == "."); + Assert.DoesNotContain(result.Value.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries), segment => segment == ".."); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLibraryNameIsADotDotSegment_ShouldReturnInvalidPath() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[1024]); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), libraryName: "..", authorName: "Author", bookTitle: "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + /// + /// Creates a real backed by a stubbed path strategy, so that the sanitization of hostile segment names is exercised. + /// + /// The created real path service. + private static IPathService CreateRealPathService() + { + IPathStrategy mockPathStrategy = Substitute.For(); + mockPathStrategy.PathSeparator.Returns(Path.DirectorySeparatorChar); + mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(Path.GetInvalidFileNameChars()); + mockPathStrategy.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(FileSystemPathId.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())).Value)); + mockPathStrategy.IsValidPath(Arg.Any()).Returns(true); + + IPlatformContext mockPlatformContext = Substitute.For(); + mockPlatformContext.PathStrategy.Returns(mockPathStrategy); + IPlatformContextManager mockPlatformContextManager = Substitute.For(); + mockPlatformContextManager.GetCurrentContext().Returns(mockPlatformContext); + + return new PathService(mockPlatformContextManager); + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs new file mode 100644 index 00000000..8dc6371d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre; + +/// +/// Contains security tests for the class, exercised through the public artwork provider surface. +/// +[ExcludeFromCodeCoverage] +public class CalibreArtworkProviderSecurityTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheCoverInsideTheBookDirectory() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithCoverReference(bookDirectory, "cover.jpg"); + File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); + IArtworkProvider provider = CreateArtworkProvider(); + + // Act + ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Theory] + [InlineData("../cover.jpg")] // parent directory escape + [InlineData("../../cover.jpg")] // multiple parent directory escape + [InlineData("sub/cover.jpg")] // forward slash path traversal + [InlineData("sub\\cover.jpg")] // backslash path traversal + [InlineData(@"C:\Windows\System32\drivers\etc\hosts")] // absolute Windows path + [InlineData("/etc/passwd")] // absolute Unix path + [InlineData("http://evil.example/cover.jpg")] // remote URL + [InlineData("file:///etc/passwd")] // file URI + public async Task GetArtworkAsync_WhenCoverHrefEscapesTheBookDirectory_ShouldReturnNull(string coverHref) + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithCoverReference(bookDirectory, coverHref); + IArtworkProvider provider = CreateArtworkProvider(); + + // Act + ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates the Calibre artwork provider by registering the plugin services and resolving the keyed artwork provider. + /// + /// The created Calibre artwork provider. + private static IArtworkProvider CreateArtworkProvider() + { + ServiceCollection services = new(); + new CalibrePlugin().RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + return serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)!; + } + + /// + /// Writes an OPF file that references the given cover into the book directory, and returns the path of the book. + /// + /// The file system path of the directory the OPF file is written into. + /// The href of the cover the OPF file references. + /// The file system path of the book. + private static string WriteBookWithCoverReference(string bookDirectory, string coverHref) + { + string opf = $$"""Test"""; + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); + return bookPath; + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs new file mode 100644 index 00000000..9930968d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre.Opf; + +/// +/// Contains security tests for the class, exercised through the public metadata provider surface. +/// +[ExcludeFromCodeCoverage] +public class OpfReaderSecurityTests +{ + private const int MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetMetadataAsync_WhenOpfContainsADoctypeWithAnExternalEntity_ShouldNotExpandTheEntity() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + // the OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded + string opfContent = """]>&xxe;"""; + string bookPath = WriteBookWithOpf(bookDirectory, opfContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandTheEntities() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string opfContent = """]>&lol3;"""; + string bookPath = WriteBookWithOpf(bookDirectory, opfContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfIsOversized_ShouldNotParseIt() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string oversizedContent = $"""{new string('a', MAX_OPF_FILE_SIZE_BYTES + 100)}"""; + string bookPath = WriteBookWithOpf(bookDirectory, oversizedContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfIsMalformedXml_ShouldNotExposeAnException() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithOpf(bookDirectory, """Unclosed"""); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + // a malformed OPF must be swallowed and must not leak an exception to the caller + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates the Calibre metadata provider by registering the plugin services and resolving the keyed metadata provider. + /// + /// The created Calibre metadata provider. + private static IMetadataProvider CreateMetadataProvider() + { + ServiceCollection services = new(); + new CalibrePlugin().RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + return serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)!; + } + + /// + /// Writes an OPF file with the given content into the book directory, and returns the path of the book. + /// + /// The file system path of the directory the OPF file is written into. + /// The content of the OPF file to write. + /// The file system path of the book. + private static string WriteBookWithOpf(string bookDirectory, string opfContent) + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opfContent); + return bookPath; + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-opf-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs new file mode 100644 index 00000000..b733d3e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly ReorderLibraryArtworkProvidersCommandHandler _sut; + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryArtworkProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List { firstProvider, secondProvider }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), + Arg.Any()); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + Guid unknownPluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List { configuration }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get configurations")); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs new file mode 100644 index 00000000..cdaa5549 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandValidatorTests +{ + private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new(); + private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { PluginIds = null! }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); + } + + [Fact] + public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { PluginIds = [] }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs new file mode 100644 index 00000000..8d6e2260 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut; + private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Fixture for generating test data. + /// + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List()); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List + { + _libraryArtworkProviderConfigurationEntityFixture.Create( + libraryId: libraryId, + pluginId: Guid.NewGuid(), + rank: 3, + isEnabled: true) + }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => !configuration.IsEnabled && configuration.Rank == 4), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create( + libraryId: Guid.NewGuid(), + pluginId: Guid.NewGuid(), + rank: 2, + isEnabled: false); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) + .Returns(existingConfiguration); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), + Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get configuration")); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpsertFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List()); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to upsert configuration")); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs new file mode 100644 index 00000000..df6d5a97 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandValidatorTests +{ + private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new(); + private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + command = command with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + command = command with { PluginId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..052052ba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs @@ -0,0 +1,231 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IPluginRepository _mockPluginRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetLibraryArtworkProvidersQueryHandler _sut; + private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetLibraryArtworkProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnProvidersOrderedByRankWithPluginNames() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), + _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) + ]; + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>(configurations)); + List plugins = + [ + _pluginEntityFixture.Create(firstPluginId), + _pluginEntityFixture.Create(secondPluginId) + ]; + _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstPluginId, result.Value[0].PluginId); + Assert.Equal(plugins[0].Name, result.Value[0].Name); + Assert.Equal(configurations[1].Rank, result.Value[0].Rank); + Assert.Equal(secondPluginId, result.Value[1].PluginId); + Assert.Equal(plugins[1].Name, result.Value[1].Name); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Guid unknownPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) + ]; + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>(configurations)); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([_pluginEntityFixture.Create()])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoConfigurationsExist_ShouldReturnEmptyList() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get configurations"); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get plugins")); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..f97132cf --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryValidatorTests +{ + private readonly GetLibraryArtworkProvidersQueryValidator _validator = new(); + private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + query = query with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs new file mode 100644 index 00000000..47de5fc4 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.Repositories.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtworkProviderConfigurationRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ArtworkProviderConfigurationRepository _sut; + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ArtworkProviderConfigurationRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new ArtworkProviderConfigurationRepository(_mockContext); + } + + [Fact] + public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value); + Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId); + } + + [Fact] + public async Task GetByLibraryIdAsync_WhenLibraryHasNoConfigurations_ShouldReturnEmptyList() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(configuration.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + + // Act + Result result = await _sut.GetByLibraryAndPluginIdAsync(libraryId, pluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + + // Act + Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(_mockContext.LibraryArtworkProviderConfigurations); + } + + [Fact] + public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); + await _mockContext.SaveChangesAsync(); + + LibraryArtworkProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5); + updatedConfiguration.IsEnabled = true; + + // Act + Result result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryArtworkProviderConfigurations.Single(); + Assert.Equal(5, retrievedConfiguration.Rank); + Assert.True(retrievedConfiguration.IsEnabled); + Assert.Equal(configuration.Id, retrievedConfiguration.Id); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs new file mode 100644 index 00000000..ee54d7b9 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs @@ -0,0 +1,541 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Infrastructure.Fixtures.Common.Setup; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkServiceTests +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly BookArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(copiedFileId)); + + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).SanitizeSegment("Unknown"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // the environment does not support creating reparse points + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound() + { + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + { + // Arrange + byte[] imageBytes = new byte[1024]; + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), + Arg.Any(), + true); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(sourcePath)); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + async Task Act() + { + await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, otherFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.DidNotReceive().DeleteFile(otherFileId); + } + + [Fact] + public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError() + { + // Arrange + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title"); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string booksPath = Path.Combine(mediaRoot, "books"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); + + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + + // every directory except the artwork directory itself already exists, so that only the final directory is created + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the book is stored into. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The expected file system path of the book artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "books", + $"{libraryName}-{libraryId}", + authorName, + $"{bookTitle}-{bookId}"); + } + + /// + /// Creates a temporary image file with the given size and returns its path. + /// + /// The size of the temporary image file, in bytes. + /// The file system path of the created temporary image file. + private static string CreateTempImageFile(int smallImageBytes) + { + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); + return sourcePath; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs new file mode 100644 index 00000000..e82c8dac --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Calibre.Fixtures.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreArtworkProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly TestMetadataLookupFixture _testMetadataLookupFixture = new(); + private readonly CalibreArtworkProvider _sut = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(LibraryType.Book, result[0]); + Assert.Equal(LibraryType.EBook, result[1]); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + Assert.Null(result.RemoteUrl); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Theory] + [InlineData("../cover.jpg")] // parent directory escape + [InlineData("sub/cover.jpg")] // path with a separator + [InlineData("sub\\cover.jpg")] // path with a backslash separator + public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref) + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """Test"""); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull() + { + // Arrange + MetadataLookupDto lookup = _testMetadataLookupFixture.Create(); + IArtworkProvider baseProvider = _sut; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + /// + /// Writes an OPF file that references the given cover into the book directory. + /// + /// The file system path of the directory the OPF file is written into. + /// The href of the cover the OPF file references. + private static void WriteOpf(string bookDirectory, string coverHref) + { + string opf = $$"""Test"""; + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs new file mode 100644 index 00000000..39e1ef2a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreBookMetadataProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly CalibreBookMetadataProvider _sut = new(); + + private const string OPF_DOCUMENT = """Test Book TitleTest Author"""; + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(LibraryType.Book, result[0]); + Assert.Equal(LibraryType.EBook, result[1]); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Test Book Title", result!.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Test Book Title", metadata.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs new file mode 100644 index 00000000..b4dfde86 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibrePluginTests +{ + private readonly CalibrePlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(CalibrePlugin.s_pluginId, result); + Assert.Equal(new Guid("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Reads book metadata and covers from the OPF files of a Calibre library.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataAndArtworkProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)); + Assert.NotNull(serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs new file mode 100644 index 00000000..297ebbad --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs @@ -0,0 +1,367 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Mapping; +using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreMapperTests +{ + private readonly OpfDocumentDtoFixture _opfDocumentDtoFixture = new(); + private readonly OpfCreatorDtoFixture _opfCreatorDtoFixture = new(); + private readonly OpfContributorDtoFixture _opfContributorDtoFixture = new(); + private readonly OpfIdentifierDtoFixture _opfIdentifierDtoFixture = new(); + + [Fact] + public void Map_WhenDocumentHasAllFields_ShouldMapThemToTheBookMetadataDto() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create( + title: "Test Book Title", + description: "

A test description with markup.

", + publisher: "Test Publisher", + publishDate: new DateTimeOffset(2015, 6, 15, 0, 0, 0, TimeSpan.Zero), + languageCode: "en", + series: "The Series", + seriesIndex: 2.5, + rating: 8, + subjects: ["Science fiction", "Space opera"], + creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", "oth")], + contributors: + [ + _opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"), + _opfContributorDtoFixture.Create("Test Translator", "trl") + ], + identifiers: + [ + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("goodreads", "123456"), + _opfIdentifierDtoFixture.Create("ASIN", "B00TEST1"), + _opfIdentifierDtoFixture.Create("lccn", "test-lccn"), + _opfIdentifierDtoFixture.Create("oclc", "ocm12345678"), + _opfIdentifierDtoFixture.Create("openlibrary", "OL100M"), + _opfIdentifierDtoFixture.Create("google", "google-id") + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("Test Book Title", result.Title); + Assert.Equal("A test description with markup .", result.Description); + Assert.Equal("Test Publisher", result.Publisher); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(2015, 6, 15), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(2015, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal("The Series", result.Series!.Title); + Assert.Equal(2.5f, result.VolumeNumber); + Assert.Equal("B00TEST1", result.ASIN); + Assert.Equal("123456", result.GoodreadsId); + Assert.Equal("test-lccn", result.LCCN); + Assert.Equal("ocm12345678", result.OCLCNumber); + Assert.Equal("OL100M", result.OpenLibraryId); + Assert.Equal("google-id", result.GoogleBooksId); + Assert.Null(result.Genres); + Assert.Null(result.CoverImagePath); + } + + [Fact] + public void Map_WhenDescriptionContainsHtmlEntities_ShouldDecodeAndStripThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: "A & B <tag>description</tag> with multiple spaces"); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("A & B description with multiple spaces", result.Description); + } + + [Fact] + public void Map_WhenDescriptionIsEmpty_ShouldReturnNullDescription() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: " "); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Description); + } + + [Theory] + [InlineData(0)] // a zero series index is not a meaningful volume number + public void Map_WhenSeriesIndexIsZero_ShouldReturnNullVolumeNumber(double seriesIndex) + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(seriesIndex: seriesIndex); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.VolumeNumber); + } + + [Fact] + public void Map_WhenSeriesIndexIsNull_ShouldReturnNullVolumeNumber() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.VolumeNumber); + } + + [Fact] + public void Map_WhenSeriesIsNull_ShouldReturnNullSeries() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Series); + } + + [Fact] + public void Map_WhenRatingIsPresent_ShouldMapItToACalibreRatingWithMaxValueTen() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(rating: 8); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + BookRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(8m, rating.Value); + Assert.Equal(10m, rating.MaxValue); + Assert.Equal(BookRatingSource.Calibre, rating.Source); + Assert.Null(rating.VoteCount); + } + + [Fact] + public void Map_WhenRatingIsMissing_ShouldReturnNullRatings() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Ratings); + } + + [Fact] + public void Map_WhenSubjectsArePresent_ShouldMapThemToTagsWithNullGenres() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(subjects: ["Science fiction", "Space opera"]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Genres); + Assert.Equal(2, result.Tags!.Count); + Assert.Equal("Science fiction", result.Tags[0].Name); + Assert.Equal("Space opera", result.Tags[1].Name); + } + + [Fact] + public void Map_WhenCreatorsAndContributorsArePresent_ShouldMapRolesAndCategories() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create( + creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", null)], + contributors: + [ + _opfContributorDtoFixture.Create("Test Translator", "trl"), + _opfContributorDtoFixture.Create("Test Illustrator", "ill"), + _opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"), + _opfContributorDtoFixture.Create("Misc Contributor", null) + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal(6, result.Contributors!.Count); + + MediaContributorDto author = result.Contributors[0]; + Assert.Equal("Test Author", author.Name!.DisplayName); + Assert.Equal("Author", author.Role!.Name); + Assert.Equal("Writing", author.Role.Category); + + MediaContributorDto coAuthor = result.Contributors[1]; + Assert.Equal("Co Author", coAuthor.Name!.DisplayName); + Assert.Equal("Author", coAuthor.Role!.Name); + Assert.Equal("Writing", coAuthor.Role.Category); + + MediaContributorDto translator = result.Contributors[2]; + Assert.Equal("Test Translator", translator.Name!.DisplayName); + Assert.Equal("trl", translator.Role!.Name); + Assert.Equal("Translation", translator.Role.Category); + + MediaContributorDto illustrator = result.Contributors[3]; + Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName); + Assert.Equal("ill", illustrator.Role!.Name); + Assert.Equal("Art", illustrator.Role.Category); + + MediaContributorDto production = result.Contributors[4]; + Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName); + Assert.Equal("bkp", production.Role!.Name); + Assert.Equal("Production", production.Role.Category); + + MediaContributorDto misc = result.Contributors[5]; + Assert.Equal("Misc Contributor", misc.Name!.DisplayName); + Assert.Equal("Contributor", misc.Role!.Name); + Assert.Equal("Other", misc.Role.Category); + } + + [Fact] + public void Map_WhenCreatorsAreDuplicatedWithTheSameRole_ShouldDeDuplicateThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Test Author", "aut")]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + MediaContributorDto author = Assert.Single(result.Contributors!); + Assert.Equal("Test Author", author.Name!.DisplayName); + } + + [Fact] + public void Map_WhenIsbnIdentifiersArePresent_ShouldNormalizeAndMapThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: + [ + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("ISBN", "0306406152"), + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("ISBN", "not-an-isbn") + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal(2, result.Isbns!.Count); + Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); + } + + [Fact] + public void Map_WhenNoIdentifiersArePresent_ShouldReturnEmptyIsbnList() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Empty(result.Isbns!); + } + + [Fact] + public void Map_WhenAmazonIdentifiersArePresent_ShouldMapAsin() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: [_opfIdentifierDtoFixture.Create("amazon", "B00TEST1")]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("B00TEST1", result.ASIN); + } + + [Fact] + public void Map_WhenLanguageCodeIsUnknown_ShouldReturnTheRawCode() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: "zz"); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("zz", result.Language!.LanguageCode); + Assert.Equal("zz", result.Language.LanguageName); + } + + [Fact] + public void Map_WhenLanguageCodeIsEmpty_ShouldReturnNullLanguage() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: " "); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Language); + } + + [Fact] + public void Map_WhenDocumentHasNoMetadata_ShouldReturnEmptyDto() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Description); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.Publisher); + Assert.Null(result.Series); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Ratings); + } + + [Fact] + public void Map_WhenPublishDateIsMissing_ShouldReturnEmptyReleaseInfo() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(publishDate: null); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + // a book without a publication date must still be enrichable, so the release info is present with empty fields + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo!.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs new file mode 100644 index 00000000..b5435fcb --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Opf; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpfReaderTests +{ + [Fact] + public void Read_WhenOpfFileContainsAllSupportedFields_ShouldParseThemAll() + { + // Arrange + string opfFilePath = CreateOpfFile("""Test Book TitleTest AuthorSecond Creatorcalibre (3.48.0) [https://calibre-ebook.com]Test Translator<p>A test description with <b>markup</b>.</p>Test Publisher2015-06-15en978-0-306-40615-7123456B00TEST1test-lccnocm12345678OL100Mgoogle-idScience fictionSpace opera"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Equal("Test Book Title", result.Title); + Assert.Equal("

A test description with markup.

", result.Description); + Assert.Equal("Test Publisher", result.Publisher); + Assert.Equal(2015, result.PublishDate!.Value.Year); + Assert.Equal(6, result.PublishDate.Value.Month); + Assert.Equal(15, result.PublishDate.Value.Day); + Assert.Equal("en", result.LanguageCode); + Assert.Equal("The Series", result.Series); + Assert.Equal(2.5, result.SeriesIndex); + Assert.Equal(8, result.Rating); + Assert.Equal("cover.jpg", result.CoverHref); + Assert.Equal(2, result.Creators.Count); + Assert.Equal("Test Author", result.Creators[0].Name); + Assert.Equal("aut", result.Creators[0].Role); + Assert.Equal(2, result.Contributors.Count); + Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", result.Contributors[0].Name); + Assert.Equal("bkp", result.Contributors[0].Role); + Assert.Equal(7, result.Identifiers.Count); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ISBN" && identifier.Value == "978-0-306-40615-7"); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "goodreads" && identifier.Value == "123456"); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ASIN" && identifier.Value == "B00TEST1"); + Assert.Equal(2, result.Subjects.Count); + Assert.Equal("Science fiction", result.Subjects[0]); + Assert.Equal("Space opera", result.Subjects[1]); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileDoesNotExist_ShouldReturnEmptyDocument() + { + // Act + OpfDocumentDto result = OpfReader.Read(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.opf")); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + Assert.Empty(result.Creators); + Assert.Empty(result.Subjects); + } + + [Fact] + public void Read_WhenMetadataContainsWhitespaceOnlyValues_ShouldSkipThem() + { + // Arrange + string opfFilePath = CreateOpfFile(""" """); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Creators); + Assert.Empty(result.Subjects); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenMetadataElementIsMissing_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = CreateOpfFile(""""""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem() + { + // Arrange + // the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title + string opfFilePath = CreateOpfFile("""]>&xxe;"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandThem() + { + // Arrange + string opfFilePath = CreateOpfFile("""]>&lol3;"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileIsOversized_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = Path.Combine(Path.GetTempPath(), $"oversized-{Guid.NewGuid():N}.opf"); + string oversizedContent = $"""{new string('a', (5 * 1024 * 1024) + 100)}"""; + File.WriteAllText(opfFilePath, oversizedContent); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileIsMalformedXml_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = CreateOpfFile("""Unclosed"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + /// + /// Creates a temporary OPF file with the given content and returns its path. + /// + /// The content of the OPF file to create. + /// The file system path of the created OPF file. + private static string CreateOpfFile(string content) + { + string opfFilePath = Path.Combine(Path.GetTempPath(), $"opf-{Guid.NewGuid():N}.opf"); + File.WriteAllText(opfFilePath, content); + return opfFilePath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj new file mode 100644 index 00000000..4309ec26 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs new file mode 100644 index 00000000..2172609c --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; + +/// +/// Contains unit tests for the interface. +/// +[ExcludeFromCodeCoverage] +public class IArtworkProviderGenericTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetArtworkAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtworkDto expectedArtwork = _artworkDtoFixture.Create(); + TestBookArtworkProvider provider = new(expectedArtwork); + IArtworkProvider baseProvider = provider; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); + + // Assert + Assert.Equal(expectedArtwork, result); + Assert.Same(lookup, provider.ReceivedLookup); + Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull() + { + // Arrange + MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); + TestBookArtworkProvider provider = new(_artworkDtoFixture.Create()); + IArtworkProvider baseProvider = provider; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Null(provider.ReceivedLookup); + } + + /// + /// Test double for the typed artwork provider interface that records the forwarded arguments. + /// + [ExcludeFromCodeCoverage] + private sealed class TestBookArtworkProvider : IArtworkProvider + { + private readonly ArtworkDto _artwork; + + /// + /// Gets the lookup that was forwarded to the typed implementation. + /// + public BookMetadataLookupDto? ReceivedLookup { get; private set; } + + /// + /// Gets the cancellation token that was forwarded to the typed implementation. + /// + public CancellationToken ReceivedCancellationToken { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The artwork returned by the typed implementation. + public TestBookArtworkProvider(ArtworkDto artwork) + { + _artwork = artwork; + } + + /// + public string Name => "Test Provider"; + + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book]; + + /// + public bool RequiresWebAccess => false; + + /// + public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ReceivedLookup = lookup; + ReceivedCancellationToken = cancellationToken; + return Task.FromResult(_artwork); + } + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..88583a22 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryArtworkProvidersEndpoint _sut; + private readonly GetLibraryArtworkProvidersRequestFixture _getLibraryArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryArtworkProviderResponses() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponses = + [ + _libraryArtworkProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1), + _libraryArtworkProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2) + ]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Library.NotFound", "The requested library was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested library was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryArtworkProvidersQueryToSender() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == request.LibraryId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..272e253b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ReorderLibraryArtworkProvidersEndpoint _sut; + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Success, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.PluginIds.SequenceEqual(request.PluginIds)), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..4668185b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; +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.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly SetLibraryArtworkProviderEnabledEndpoint _sut; + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Success, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.PluginId == request.PluginId && + command.IsEnabled == request.IsEnabled), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} From 66871ccf621ed2aa20c25652bf74f4d2675ade1d Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:18:40 -0700 Subject: [PATCH 3/7] Adds metadata aggregation to the media library enrichment job --- .../Common/DTO/Filtering/LibraryFilterDto.cs | 2 +- .../MediaLibrary/Management/LibraryEntity.cs | 2 +- .../UsersManagement/UserSettingsEntity.cs | 7 +- .../Common/DataAccess/UoW/IUnitOfWork.cs | 10 + .../DTO/Configuration/MediaSettingsDto.cs | 5 + .../AddMediaLibraryRequestMapping.cs | 5 +- .../Management/LibraryEntityMapping.cs | 10 +- .../MediaLibrary/Management/LibraryMapping.cs | 8 +- .../Management/UpdateLibraryRequestMapping.cs | 3 +- .../Users/UpdateUserSettingsRequestMapping.cs | 6 +- .../Users/UserSettingsEntityMapping.cs | 14 +- .../Users/UserSettingsMapping.cs | 11 +- .../Commands/AddLibrary/AddLibraryCommand.cs | 5 +- .../AddLibrary/AddLibraryCommandHandler.cs | 11 +- .../UpdateLibrary/UpdateLibraryCommand.cs | 4 +- .../UpdateLibraryCommandHandler.cs | 13 +- .../LibraryScanQueuedDomainEventHandler.cs | 2 +- ...rLibraryMetadataProvidersCommandHandler.cs | 27 +- ...ibraryMetadataProvidersCommandValidator.cs | 3 + ...ryMetadataProviderEnabledCommandHandler.cs | 27 +- ...MetadataProviderEnabledCommandValidator.cs | 5 + .../UpdatePluginSettingsCommandValidator.cs | 3 + ...GetLibraryMetadataProvidersQueryHandler.cs | 35 +- ...tLibraryMetadataProvidersQueryValidator.cs | 26 ++ .../GetPluginSettingsQueryHandler.cs | 13 +- .../GetPluginSettingsQueryValidator.cs | 26 ++ .../UpdateUserSettingsCommand.cs | 8 +- .../UpdateUserSettingsCommandHandler.cs | 13 +- .../Management/AddLibraryRequest.cs | 4 +- .../Management/UpdateLibraryRequest.cs | 6 +- .../Settings/UpdateUserSettingsRequest.cs | 8 +- .../Management/LibraryResponse.cs | 7 +- .../Settings/UserSettingsResponse.cs | 8 +- .../Configuration/LibraryConfiguration.cs | 2 +- .../UserSettingsConfiguration.cs | 7 +- .../Core/Repositories/Books/BookRepository.cs | 18 +- .../BookAlphaFilterSpecification.cs | 10 +- .../Core/UoW/LuminaDbContext.cs | 1 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 21 + .../FileSystemStructureSeedService.cs | 43 +- .../LibraryAggregate/Library.cs | 20 +- .../Services/IMediaLibraryScanningService.cs | 3 +- .../Services/MediaLibraryScanningService.cs | 9 +- .../Services/Scanners/IMediaTypeScanner.cs | 3 +- .../UserSettingsAggregate/UserSettings.cs | 58 ++- .../Common/Errors/Errors.Configuration.cs | 1 + .../Validators/MediaSettingsDtoValidator.cs | 4 + .../MediaLibraryScanMetadataEnrichmentJob.cs | 335 +++++++++++--- .../Jobs/Common/MetadataAggregator.cs | 127 +++++ .../appsettings.shared.json | 3 +- .../AddLibrary/AddLibraryEndpointSummary.cs | 8 +- .../GetEnabledLibrariesEndpointSummary.cs | 4 +- .../GetLibrariesEndpointSummary.cs | 4 +- .../GetLibrary/GetLibraryEndpointSummary.cs | 4 +- .../UpdateLibraryEndpointSummary.cs | 8 +- .../GetUserSettingsEndpointSummary.cs | 5 +- .../UpdateUserSettingsEndpointSummary.cs | 7 +- .../Common/DTO/Libraries/LibraryDto.cs | 3 +- .../DTO/UsersManagement/UserSettingsDto.cs | 7 +- .../SaveLibrary/SaveLibraryEndpointSummary.cs | 3 +- .../UpdateUserSettingsEndpointSummary.cs | 3 +- .../Views/Library/Management/Item.ar-SA.resx | 6 +- .../Views/Library/Management/Item.de-DE.resx | 4 +- .../Views/Library/Management/Item.en-US.resx | 4 +- .../Views/Library/Management/Item.es-ES.resx | 4 +- .../Views/Library/Management/Item.fr-FR.resx | 4 +- .../Views/Library/Management/Item.it-IT.resx | 4 +- .../Views/Library/Management/Item.ja-JP.resx | 4 +- .../Views/Library/Management/Item.resx | 4 +- .../Views/Library/Management/Item.ro-RO.resx | 4 +- .../Views/Library/Management/Item.uk-UA.resx | 6 +- .../Views/Library/Management/Item.zh-CN.resx | 4 +- .../Resources/Views/Tools/Settings.ar-SA.resx | 6 +- .../Resources/Views/Tools/Settings.de-DE.resx | 4 +- .../Resources/Views/Tools/Settings.en-US.resx | 4 +- .../Resources/Views/Tools/Settings.es-ES.resx | 4 +- .../Resources/Views/Tools/Settings.fr-FR.resx | 4 +- .../Resources/Views/Tools/Settings.it-IT.resx | 4 +- .../Resources/Views/Tools/Settings.ja-JP.resx | 4 +- .../Core/Resources/Views/Tools/Settings.resx | 4 +- .../Resources/Views/Tools/Settings.ro-RO.resx | 4 +- .../Resources/Views/Tools/Settings.uk-UA.resx | 6 +- .../Resources/Views/Tools/Settings.zh-CN.resx | 4 +- .../Core/Views/Library/Management/Item.cshtml | 10 +- .../Core/Views/Tools/Settings.cshtml | 17 +- .../LibraryContentLocationEntityFixture.cs | 42 ++ .../Management/LibraryEntityFixture.cs | 6 +- ...adataProviderConfigurationEntityFixture.cs | 9 +- .../Entities/Plugins/PluginEntityFixture.cs | 17 +- .../UserSettingsEntityFixture.cs | 13 +- .../Configuration/MediaSettingsDtoFixture.cs | 48 ++ .../AddLibrary/AddLibraryCommandFixture.cs | 7 +- .../UpdateLibraryCommandFixture.cs | 6 +- .../UpdateUserSettingsCommandFixture.cs | 12 +- .../Management/AddLibraryRequestFixture.cs | 7 +- .../Management/UpdateLibraryRequestFixture.cs | 6 +- .../UpdateUserSettingsRequestFixture.cs | 52 +++ .../Management/LibraryResponseFixture.cs | 6 +- .../LibraryMetadataProviderResponseFixture.cs | 50 ++ .../Settings/UserSettingsResponseFixture.cs | 56 +++ .../LibraryAggregate/LibraryFixture.cs | 8 +- .../UserSettingsFixture.cs | 13 +- .../Common/DTO/Libraries/LibraryDtoFixture.cs | 13 +- .../DTO/Libraries/ScanLibraryDtoFixture.cs | 43 ++ .../LibraryMetadataProviderDtoFixture.cs | 52 +++ .../PluginSettingDescriptorDtoFixture.cs | 55 +++ .../DTO/Plugins/PluginSettingsDtoFixture.cs | 55 +++ .../UsersManagement/UserSettingsDtoFixture.cs | 23 +- ...rLibraryMetadataProvidersRequestFixture.cs | 46 ++ ...ryMetadataProviderEnabledRequestFixture.cs | 49 ++ .../UpdatePluginSettingsRequestFixture.cs | 9 +- ...etLibraryMetadataProvidersEndpointTests.cs | 54 +-- .../GetPluginSettingsEndpointTests.cs | 33 +- ...erLibraryMetadataProvidersEndpointTests.cs | 51 +- ...aryMetadataProviderEnabledEndpointTests.cs | 67 ++- .../UpdatePluginSettingsEndpointTests.cs | 46 +- .../GetUserSettingsEndpointTests.cs | 21 +- .../UpdateUserSettingsEndpointTests.cs | 37 +- ...a.Presentation.Api.IntegrationTests.csproj | 1 + .../GetUserSettingsEndpointTests.cs | 58 +++ .../Settings/SettingsViewEndpointTests.cs | 46 ++ .../UpdateUserSettingsEndpointTests.cs | 76 +++ ...etLibraryMetadataProvidersEndpointTests.cs | 40 +- .../GetPluginSettingsEndpointTests.cs | 32 +- ...erLibraryMetadataProvidersEndpointTests.cs | 50 +- ...aryMetadataProviderEnabledEndpointTests.cs | 54 +-- .../UpdatePluginSettingsEndpointTests.cs | 44 +- .../GetUserSettingsEndpointTests.cs | 23 +- .../UpdateUserSettingsEndpointTests.cs | 58 ++- .../GetUserSettingsEndpointTests.cs | 46 ++ .../Settings/SettingsViewEndpointTests.cs | 41 ++ .../UpdateUserSettingsEndpointTests.cs | 76 +++ .../AddMediaLibraryRequestMappingTests.cs | 87 ++-- .../Management/LibraryEntityMappingTests.cs | 107 ++--- .../Management/LibraryMappingTests.cs | 9 +- .../UpdateUserSettingsRequestMappingTests.cs | 13 +- .../Users/UserSettingsEntityMappingTests.cs | 4 +- .../Users/UserSettingsMappingTests.cs | 4 +- ...aryMetadataProvidersCommandHandlerTests.cs | 69 ++- ...adataProviderEnabledCommandHandlerTests.cs | 88 +++- ...UpdatePluginSettingsCommandHandlerTests.cs | 8 +- ...braryMetadataProvidersQueryHandlerTests.cs | 75 ++- ...aryMetadataProvidersQueryValidatorTests.cs | 49 ++ .../GetPluginSettingsQueryHandlerTests.cs | 30 +- .../GetPluginSettingsQueryValidatorTests.cs | 49 ++ .../UpdateUserSettingsCommandHandlerTests.cs | 4 +- .../GetUserSettingsQueryHandlerTests.cs | 14 +- .../Lumina.Application.UnitTests.csproj | 1 + .../Management/AddLibraryRequestTests.cs | 46 +- .../Management/UpdateLibraryRequestTests.cs | 54 +-- .../UpdateUserSettingsRequestTests.cs | 23 +- .../Management/LibraryResponseTests.cs | 4 +- .../Settings/UserSettingsResponseTests.cs | 25 +- .../LibraryConfigurationTests.cs | 2 +- .../UserSettingsConfigurationTests.cs | 2 +- .../Repositories/Books/BookRepositoryTests.cs | 62 +-- .../Core/UoW/LuminaDbContextTests.cs | 21 +- .../Core/UoW/UnitOfWorkTests.cs | 26 +- .../LibraryAggregate/LibraryTests.cs | 12 +- .../UserSettingsTests.cs | 21 +- ...iaLibraryScanMetadataEnrichmentJobTests.cs | 435 ++++++++++++++++++ .../Jobs/Common/MetadataAggregatorTests.cs | 332 +++++++++++++ .../Lumina.Infrastructure.UnitTests.csproj | 1 + ...etLibraryMetadataProvidersEndpointTests.cs | 6 +- .../GetPluginSettingsEndpointTests.cs | 14 +- .../GetUserSettingsEndpointTests.cs | 8 +- .../UpdateUserSettingsEndpointTests.cs | 12 +- .../UpdateUserSettingsEndpointTests.cs | 10 +- 168 files changed, 3503 insertions(+), 1062 deletions(-) create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs index 6b77d3dc..c13e4250 100644 --- a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs +++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs @@ -25,5 +25,5 @@ public record LibraryFilterDto : BaseFilterDto /// /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; init; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; init; } } diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index ef17ab05..a7c07954 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -63,7 +63,7 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; init; } + public bool CanDownloadMetadataFromWeb { get; init; } /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 524544bb..5e8de0bf 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -35,13 +35,18 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; set; } = true; + /// + /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index dc49b1f4..17a48b83 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -71,6 +71,11 @@ public interface IUnitOfWork /// ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; } + /// + /// Gets the library artwork provider configuration repository. + /// + IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; } + /// /// Gets the plugin repository. /// @@ -97,6 +102,11 @@ public interface IUnitOfWork /// Cancellation token that can be used to stop the execution. Task SaveChangesAsync(CancellationToken cancellationToken); + /// + /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. + /// + void ClearTrackedEntities(); + /// /// Begins a new database transaction. /// diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs index f68feee4..c77c25f4 100644 --- a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs @@ -21,4 +21,9 @@ public class MediaSettingsDto /// Gets or sets the directory where media library files are stored. ///
public required string LibrariesDirectory { get; init; } + + /// + /// Gets or sets the directory where the media item files are stored. + /// + public required string BooksDirectory { get; init; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index 8e74f24c..f524961e 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Contracts.Requests.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -27,7 +24,7 @@ public static class AddMediaLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMetadataFromWeb, + request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 1484cf34..fe652e54 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.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.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -29,11 +29,11 @@ public static class LibraryEntityMapping repositoryEntity.UserId, repositoryEntity.Title, repositoryEntity.LibraryType, - repositoryEntity.ContentLocations.Select(location => location.Path).ToList(), + [.. repositoryEntity.ContentLocations.Select(location => location.Path)], repositoryEntity.CoverImage, repositoryEntity.IsEnabled, repositoryEntity.IsLocked, - repositoryEntity.DownloadMetadataFromWeb, + repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, repositoryEntity.CreatedOnUtc, @@ -59,10 +59,10 @@ public static class LibraryEntityMapping repositoryEntity.CoverImage, repositoryEntity.IsEnabled, repositoryEntity.IsLocked, - repositoryEntity.DownloadMetadataFromWeb, + repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, - repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList() + [.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index dac14f8a..90f36343 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -25,14 +25,14 @@ public static class LibraryMapping Title = domainEntity.Title, LibraryType = domainEntity.LibraryType, UserId = domainEntity.UserId.Value, - ContentLocations = domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path }).ToList(), + ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })], CoverImage = domainEntity.CoverImage, IsEnabled = domainEntity.IsEnabled, IsLocked = domainEntity.IsLocked, - DownloadMetadataFromWeb = domainEntity.DownloadMetadataFromWeb, + CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan, - LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() + LibraryScans = [.. domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() { Id = scanId.Value, LibraryId = domainEntity.Id.Value, @@ -43,7 +43,7 @@ public static class LibraryMapping CreatedBy = default, CreatedOnUtc = default, UpdatedBy = default, - }).ToList(), + })], CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index c0dfc446..374f9e15 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -27,7 +26,7 @@ public static class UpdateLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMetadataFromWeb, + request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index 23504a3c..aff25a7d 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -20,7 +20,9 @@ public static class UpdateUserSettingsRequestMapping return new UpdateUserSettingsCommand( request.IsPaginationEnabled, request.ItemsPerPage, - request.IgnoreThePrefixForAlphaPicker, - request.IsThemeCachingEnabled); + request.ShouldIgnoreThePrefixForAlphaPicker, + request.IsThemeCachingEnabled, + request.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index b96f8fdb..b53990fd 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; @@ -28,8 +28,10 @@ public static class UserSettingsEntityMapping UserId.Create(repositoryEntity.UserId), repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker, - repositoryEntity.IsThemeCachingEnabled); + repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled, + repositoryEntity.ShouldAggregateMetadataWhenMissing + ); } /// @@ -43,7 +45,9 @@ public static class UserSettingsEntityMapping repositoryEntity.UserId, repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker, - repositoryEntity.IsThemeCachingEnabled); + repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled, + repositoryEntity.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index 7a22ee1e..cde37e56 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -24,8 +24,9 @@ public static class UserSettingsMapping UserId = domainEntity.UserId.Value, IsPaginationEnabled = domainEntity.IsPaginationEnabled, ItemsPerPage = domainEntity.ItemsPerPage, - IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker, - IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled + ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker, + IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled, + ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing }; } @@ -40,7 +41,9 @@ public static class UserSettingsMapping domainEntity.UserId.Value, domainEntity.IsPaginationEnabled, domainEntity.ItemsPerPage, - domainEntity.IgnoreThePrefixForAlphaPicker, - domainEntity.IsThemeCachingEnabled); + domainEntity.ShouldIgnoreThePrefixForAlphaPicker, + domainEntity.IsThemeCachingEnabled, + domainEntity.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index a9345eca..995a3ee6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; using System.Diagnostics; #endregion @@ -15,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [DebuggerDisplay("Title: {Title}")] @@ -26,7 +25,7 @@ public record AddLibraryCommand( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 320cd84f..c4ad4181 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; 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.Infrastructure.Authentication; @@ -10,14 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Collections.Generic; using System.Threading; @@ -113,7 +112,7 @@ public class AddLibraryCommandHandler : ICommandHandlerThe path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [DebuggerDisplay("Title: {Title}")] @@ -30,7 +30,7 @@ public record UpdateLibraryCommand( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 1e13108a..8a210168 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; 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.Infrastructure.Authentication; @@ -11,16 +9,17 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -127,10 +126,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id)).ToList() + [.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); if (createLibraryResult.IsFailure) return createLibraryResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 301727f5..d77ae07f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -60,7 +60,7 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler startScanResult = await _mediaLibraryScanningService.StartScanAsync( - libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false); + libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false); if (startScanResult.IsFailure) throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index b04e7a35..8fc10e5b 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -1,15 +1,18 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; @@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. - public ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator validator) + public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; _validator = validator; } @@ -47,6 +56,18 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 0) return validationResult; + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can reorder the metadata providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs index 1a9fd05c..95c01884 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; +using System; #endregion namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; @@ -18,6 +19,8 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator { RuleFor(command => command.LibraryId) .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); RuleFor(command => command.PluginIds) diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index d3d8eee5..21e21978 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -1,15 +1,18 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; @@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler> { private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. - public SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator validator) + public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; _validator = validator; } @@ -47,6 +56,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 0) return validationResult; + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can configure the metadata providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + Result getConfigurationResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs index f631bc44..b910702f 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; +using System; #endregion namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; @@ -18,10 +19,14 @@ public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidat { RuleFor(command => command.LibraryId) .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); RuleFor(command => command.PluginId) .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) .WithError(Errors.Plugins.PluginIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs index 283e4bf5..c100995f 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; using Lumina.Domain.Common.Errors; +using System; #endregion namespace Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; @@ -18,6 +19,8 @@ public class UpdatePluginSettingsCommandValidator : AbstractValidator command.PluginId) .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) .WithError(Errors.Plugins.PluginIdCannotBeEmpty); } } diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 6ed087fe..391cf371 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -1,16 +1,20 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; @@ -21,14 +25,23 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler>> { private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; /// /// Initializes a new instance of the class. /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. /// Injected unit of work for interacting with the data access layer repositories. - public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; + _validator = validator; } /// @@ -41,6 +54,22 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + + // an authenticated request must always carry a user identity + Guid? currentUserId = _currentUserService.UserId; + if (currentUserId is null) + return ApplicationErrors.Authorization.NotAuthorized; + Guid userId = currentUserId.Value; + + // admins can read the metadata providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs new file mode 100644 index 00000000..931c1ae3 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryMetadataProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryMetadataProvidersQueryValidator() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index 5e26b31d..28a8eae3 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -1,13 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Plugins.Contracts.Core.Plugins; using System.Collections.Generic; using System.Linq; @@ -24,16 +24,19 @@ public class GetPluginSettingsQueryHandler : IQueryHandler _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. /// Injected manager of the plugins loaded by the host application. - public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager) + /// Injected validator for application validation rules. + public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager, IValidator validator) { _unitOfWork = unitOfWork; _pluginManager = pluginManager; + _validator = validator; } /// @@ -46,6 +49,10 @@ public class GetPluginSettingsQueryHandler : IQueryHandler public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) return getPluginResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs new file mode 100644 index 00000000..2a94c3b5 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Domain.Common.Errors; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Validates the needed validation rules for . +/// +public class GetPluginSettingsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsQueryValidator() + { + RuleFor(query => query.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index 0e798ccc..e29088bf 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -9,11 +9,13 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 3028518b..9af3a222 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using System; @@ -72,8 +71,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( command.IsPaginationEnabled, command.ItemsPerPage, - command.IgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled); + command.ShouldIgnoreThePrefixForAlphaPicker, + command.IsThemeCachingEnabled, + command.ShouldAggregateMetadataWhenMissing); if (updateSettingsResult.IsFailure) return updateSettingsResult.Errors; diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index bfc717ba..df43eb8d 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -13,7 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [DebuggerDisplay("Title: {Title}")] @@ -24,7 +24,7 @@ public record AddLibraryRequest( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index ad62394a..9590f10a 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics; -using System.Runtime.InteropServices; #endregion namespace Lumina.Contracts.Requests.MediaLibrary.Management; @@ -18,7 +16,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [DebuggerDisplay("Title: {Title}")] @@ -31,7 +29,7 @@ public record class UpdateLibraryRequest( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index 2b0ad237..b37216ac 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -9,12 +9,14 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// /// Whether pagination is enabled for the user, or not. Required. /// The number of library items displayed per page when pagination is enabled. Required. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. /// Whether the theme data served to this user is cached, or not. Required. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] public sealed record UpdateUserSettingsRequest( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 9ec7de01..9dff6ddc 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -16,6 +16,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// The type of the media library. /// The file system paths of the directories where the media library elements are located. /// The path of the image file used as the cover for the library. +/// Whether the media library is enabled or not. A disabled media library is never shown or changed. +/// Whether the media library is locked or not. A locked media library is displayed, but is never changed or updated. +/// Whether the media library should update the metadata of its elements from the web, or not. +/// Whether the media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan. /// The date and time when the library was created. /// The optional date and time when the library was updated. [DebuggerDisplay("Title: {Title}")] @@ -28,7 +33,7 @@ public record LibraryResponse( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, DateTime CreatedOnUtc, diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 3c362b34..3f5c59e3 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -11,13 +11,15 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// The unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. [DebuggerDisplay("UserId: {UserId}")] public sealed record UserSettingsResponse( Guid UserId, bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ); diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 6e085ae3..8c27891a 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -46,7 +46,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration builder.Property(library => library.IsLocked) .HasColumnOrder(5); - builder.Property(library => library.DownloadMetadataFromWeb) + builder.Property(library => library.CanDownloadMetadataFromWeb) .HasDefaultValue(true) .HasColumnOrder(6); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index ca160a72..84a4f221 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -2,7 +2,6 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; #endregion namespace Lumina.DataAccess.Common.Configuration; @@ -43,10 +42,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.IgnoreThePrefixForAlphaPicker) + builder.Property(settings => settings.ShouldIgnoreThePrefixForAlphaPicker) .IsRequired() .HasColumnOrder(4); + builder.Property(settings => settings.ShouldAggregateMetadataWhenMissing) + .IsRequired() + .HasColumnOrder(10); + builder.Property(settings => settings.IsThemeCachingEnabled) .IsRequired() .HasColumnOrder(9); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index e2927044..1d369cef 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -132,7 +132,7 @@ internal sealed class BookRepository : IBookRepository booksQuery = booksQuery.Where(filterSpecification.ToExpression()); // apply sorting based on the specified sortBy and sortOrder parameters - booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.IgnoreThePrefixForAlphaPicker); + booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); // if no pagination was requested, return all the books of the library if (paginationData is null) @@ -261,8 +261,8 @@ internal sealed class BookRepository : IBookRepository /// The query to sort. /// The field to sort by (case-insensitive). /// The direction of the sorting. - /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. - private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool ignoreThePrefixForAlphaPicker) + /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. + private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker) { return sortBy?.ToLower() switch { @@ -276,8 +276,8 @@ internal sealed class BookRepository : IBookRepository ? booksQuery.OrderByDescending(book => book.MetadataProvider) : booksQuery.OrderBy(book => book.MetadataProvider), _ => sortOrder == SortOrder.Descending - ? booksQuery.OrderByDescending(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)) - : booksQuery.OrderBy(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)), + ? booksQuery.OrderByDescending(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)) + : booksQuery.OrderBy(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)), }; } @@ -286,9 +286,9 @@ internal sealed class BookRepository : IBookRepository /// the title lowercased, falling back to the original title when the title is or empty, and optionally /// stripped of a leading "the " prefix. /// - /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. + /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. /// An expression that evaluates to the title sort key of a book. - private static Expression> BuildTitleSortKey(bool ignoreThePrefixForAlphaPicker) + private static Expression> BuildTitleSortKey(bool shouldIgnoreThePrefixForAlphaPicker) { ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book"); @@ -306,7 +306,7 @@ internal sealed class BookRepository : IBookRepository // when ignoring the "The " prefix, strip a leading "the " from the lowercased title Expression effectiveTitle = lowerTitle; - if (ignoreThePrefixForAlphaPicker) + if (shouldIgnoreThePrefixForAlphaPicker) { MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the ")); MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4)); @@ -332,7 +332,7 @@ internal sealed class BookRepository : IBookRepository // include the alpha key filter, if provided if (libraryFilter.FilterAlphaKey is not null) { - BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker); + BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); filterSpecification = filterSpecification is null ? alphaFilterSpecification : filterSpecification.And(alphaFilterSpecification); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs index 460726ec..39731c29 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs @@ -23,17 +23,17 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification /// Initializes a new instance of the class. ///
/// The alpha key to filter by. A single ASCII letter, , or . - /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. - public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker) + /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + public BookAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker) { _filterAlphaKey = filterAlphaKey; - _ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + _shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; } /// @@ -82,7 +82,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification RolePermissions { get; set; } = null!; public virtual DbSet Plugins { get; set; } = null!; public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!; + public virtual DbSet LibraryArtworkProviderConfigurations { get; set; } = null!; public virtual DbSet Themes { get; set; } = null!; /// diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 0a23313a..96cc1296 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository; private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository; private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; + private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository; private IPluginRepository? _pluginRepository; private IThemeRepository? _themeRepository; private IUserRepository? _userRepository; @@ -176,6 +177,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the library artwork provider configuration repository. + /// + public IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository + { + get + { + _artworkProviderConfigurationRepository ??= new ArtworkProviderConfigurationRepository(_luminaDbContext); + return _artworkProviderConfigurationRepository; + } + } + /// /// Gets the plugin repository. /// @@ -242,6 +255,14 @@ public class UnitOfWork : IUnitOfWork, IDisposable await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. + /// + public void ClearTrackedEntities() + { + _luminaDbContext.ChangeTracker.Clear(); + } + /// /// Begins a new database transaction. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs index 24249be1..c4eeea2d 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; #endregion @@ -38,23 +37,41 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService if (rootPathIdResult.IsFailure) return rootPathIdResult.Errors; - // create the libraries directory - Result librariesPathResult = _pathService.CombinePath(rootPath, "libraries"); - if (librariesPathResult.IsFailure) - return librariesPathResult.Errors; + Result createLibrariesDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "libraries"); + if (createLibrariesDirectoryResult.IsFailure) + return createLibrariesDirectoryResult.Errors; - Result libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); - if (libraryPathIdResult.IsFailure) - return libraryPathIdResult.Errors; + Result createBooksDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "books"); + if (createBooksDirectoryResult.IsFailure) + return createBooksDirectoryResult.Errors; - Result librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value); - if (librariesDirectoryExistsResult.IsFailure) - return librariesDirectoryExistsResult.Errors; + return Result.Created; + } + + /// + /// Creates the directory with the provided under the , when it does not already exist. + /// + /// The id of the root path under which the directory is created. + /// The name of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(FileSystemPathId rootPathId, string directoryName) + { + Result directoryPathResult = _pathService.CombinePath(rootPathId.Path, directoryName); + if (directoryPathResult.IsFailure) + return directoryPathResult.Errors; + + Result directoryPathIdResult = FileSystemPathId.Create(directoryPathResult.Value); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; // only create it if it doesn't already exist - if (!librariesDirectoryExistsResult.Value) + if (!directoryExistsResult.Value) { - Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries"); + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName); if (createDirectoryResult.IsFailure) return createDirectoryResult.Errors; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 445d175c..c49151d9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -63,7 +63,7 @@ public class Library : AggregateRoot /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; private set; } = true; + public bool CanDownloadMetadataFromWeb { get; private set; } = true; /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. @@ -97,7 +97,7 @@ public class Library : AggregateRoot /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -110,7 +110,7 @@ public class Library : AggregateRoot string? coverImage, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) : base(id) @@ -122,7 +122,7 @@ public class Library : AggregateRoot CoverImage = coverImage; IsEnabled = isEnabled; IsLocked = isLocked; - DownloadMetadataFromWeb = downloadMetadataFromWeb; + CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb; ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories; ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan; _scanIds = scanIds; @@ -138,7 +138,7 @@ public class Library : AggregateRoot /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -153,7 +153,7 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) @@ -176,7 +176,7 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, scanIds @@ -194,7 +194,7 @@ public class Library : AggregateRoot /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -210,7 +210,7 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) @@ -233,7 +233,7 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, scanIds diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs index e50f05f1..80f1dacd 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs @@ -17,10 +17,9 @@ public interface IMediaLibraryScanningService /// /// The media library scan to start. /// The type of the media library to be scanned. - /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken); + Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken); /// /// Cancels . diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 2132a9da..211282ad 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; @@ -9,6 +8,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Threading; @@ -55,10 +55,9 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// /// The media library scan to start. /// The type of the media library to be scanned. - /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken) + public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken) { // mark the scan itself as started Result startScanResult = scan.StartScan(); @@ -81,7 +80,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType); // get the list of scan jobs for the retrieved scanner. It is impotant to enumerate them here, because deferred execuction would destroy any graph relationships // and properties we might set before putting the jobs on the in-memory queue. - List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMetadataFromWeb)]; + List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId)]; // count total jobs in the chain by traversing the job graph int totalJobs = CountTotalJobs(jobs); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs index af55a807..c0027ad4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs @@ -21,7 +21,6 @@ public interface IMediaTypeScanner /// Creates the media library scan jobs for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// Whether the library permits downloading data from the web, or not. /// A collection of media library scan jobs. - IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb); + IEnumerable CreateScanJobsForLibrary(LibraryId libraryId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 6cd60fc9..b463dd44 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -4,7 +4,6 @@ using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; -using System; using System.Diagnostics; #endregion @@ -20,6 +19,7 @@ public class UserSettings : AggregateRoot private const int DEFAULT_ITEMS_PER_PAGE = 48; private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false; private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true; + private const bool DEFAULT_AGGREGATE_METADATA_WHEN_MISSING = false; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -39,13 +39,18 @@ public class UserSettings : AggregateRoot /// /// Gets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; private set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; private set; } /// /// Gets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; private set; } + /// + /// Gets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -53,21 +58,24 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. private UserSettings( UserSettingsId id, UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) : base(id) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) : base(id) { UserId = userId; IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; } /// @@ -78,7 +86,7 @@ public class UserSettings : AggregateRoot /// public static Result Create() { - return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); + return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING); } /// @@ -90,7 +98,7 @@ public class UserSettings : AggregateRoot /// public static Result Create(UserId userId) { - return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); + return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING); } /// @@ -99,8 +107,9 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// /// An containing either a successfully created , or an error message. /// @@ -108,8 +117,9 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; @@ -119,8 +129,9 @@ public class UserSettings : AggregateRoot userId, isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker, - isThemeCachingEnabled); + shouldIgnoreThePrefixForAlphaPicker, + isThemeCachingEnabled, + shouldAggregateMetadataWhenMissing); } /// @@ -130,8 +141,9 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// /// An containing either a successfully created , or an error message. /// @@ -140,13 +152,14 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker, isThemeCachingEnabled); + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing); } /// @@ -154,22 +167,25 @@ public class UserSettings : AggregateRoot /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// An representing either a successful update, or an error. public Result UpdateSettings( bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; return Result.Updated; } } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 1c41488f..60244347 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -14,6 +14,7 @@ public static partial class Errors public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty)); public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty)); public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty)); + public static Error MediaBooksDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaBooksDirectoryCannotBeEmpty)); public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty)); public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String)); public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs index 846b2d86..3c3b9829 100644 --- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs @@ -23,5 +23,9 @@ public class MediaSettingsDtoValidator : AbstractValidator RuleFor(settings => settings.LibrariesDirectory) .NotEmpty() .WithError(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty); + + RuleFor(settings => settings.BooksDirectory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.MediaBooksDirectoryCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 2f650ac8..7548e7a7 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; @@ -77,71 +80,140 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the metadata providers configured for the media library, in their configured order, that support the media library type + // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // get the metadata providers configured for the media library, in their configured order, that support the media library type, + // skipping the providers that require access to the web when the media library does not permit downloading data from the web Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); - List providers = []; + List providers = []; foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryType == LibraryType.Book)]; + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; if (configuredProviders.Count == 0) _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); providers.AddRange(configuredProviders); } + // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // get the artwork providers configured for the media library, in their configured order, that support the media library type. + // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the metadata enrichment from proceeding + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + artworkProviders.AddRange(configuredProviders); + } + } + } + + IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); + // count the books that need their metadata enriched, for progress reporting purposes - Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsFailure) - throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); - int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - - // set the initial progress of the scan job - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedBooksCount = 0; string? lastPath = null; - // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size - while (true) + // when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely + if (providers.Count > 0) { - cancellationToken.ThrowIfCancellationRequested(); + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsFailure) - throw new InvalidOperationException(getBooksPageResult.FirstError.Description); - IReadOnlyList booksPage = getBooksPageResult.Value; - if (booksPage.Count == 0) - break; + // set the initial progress of the scan job + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - foreach (BookEntity bookEntity in booksPage) + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size + while (true) { cancellationToken.ThrowIfCancellationRequested(); - await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; - // check if enough time has passed since last update - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + foreach (BookEntity bookEntity in booksPage) { - // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastUpdateTime = now; - } - } + cancellationToken.ThrowIfCancellationRequested(); - lastPath = booksPage[^1].Path; + await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); + + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + unitOfWork.ClearTrackedEntities(); + + lastPath = booksPage[^1].Path; + } + } + else + { + _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // persist the changes when no page was processed, so that the scan still saves even when there are no books to enrich + if (lastPath is null) + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; @@ -166,21 +238,29 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } /// - /// Enriches the metadata of the provided , using the provided in their configured order. + /// Enriches the metadata and the artwork of the provided , using the provided metadata and artwork providers in their configured order. /// - /// The book whose metadata is enriched. - /// The metadata providers, in their configured order. - /// The repository used to persist the enriched metadata. + /// The book whose metadata and artwork are enriched. + /// The metadata providers, in their configured order. + /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The name of the media library the book belongs to. + /// The repository used to persist the enriched book. /// Cancellation token that can be used to stop the execution. - private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList providers, IBookRepository bookRepository, CancellationToken cancellationToken) + private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken) { + // when no metadata provider is available, the book must not be marked as failed to enrich, so the enrichment is skipped + if (metadataProviders.Count == 0) + return; + // convert the book to a domain object Result getBookResult = bookEntity.ToDomainEntity(); if (getBookResult.IsFailure) return; Book book = getBookResult.Value; - BookMetadataLookupDto lookup = new( + BookMetadataLookupDto bookMetadataLookup = new( LibraryId: bookEntity.LibraryId, Path: bookEntity.Path, Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results @@ -190,24 +270,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo LanguageCode: bookEntity.LanguageCode ); - // try the metadata providers in order, until one returns usable metadata - foreach (IRemoteMetadataProvider provider in providers) + BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing + ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false) + : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false); + + if (appliedMetadata is null) + { + // no metadata provider returned usable metadata, mark the book as failed to enrich + book.MarkMetadataAsFailed(); + Result markFailedResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (markFailedResult.IsFailure) + _logger.LogWarning("Failed to persist the failed enrichment state of the book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + return; + } + + // resolve the artwork of the book from the artwork providers, in their configured order + await EnrichBookArtworkAsync(book, appliedMetadata, artworkProviders, bookArtworkService, libraryName, cancellationToken).ConfigureAwait(false); + + Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateBookResult.IsFailure) + _logger.LogWarning("Failed to persist the enriched book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + } + + /// + /// Tries the in order, applying the metadata of the first one that returns usable metadata. + /// + /// The book onto which the metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied metadata, or when no provider returned usable metadata. + private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + foreach (IMetadataProvider metadataProvider in metadataProviders) { try { - MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - Result applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow); + Result applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow); if (applyMetadataResult.IsFailure) continue; + return bookMetadata; + } + catch (Exception) + { + // a failing metadata provider must not prevent the other providers from being tried + } + } + return null; + } - Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateBookResult.IsFailure) + /// + /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones. + /// + /// The book onto which the aggregated metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied aggregated metadata, or when no provider returned usable metadata. + private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + BookMetadataDto? mergedMetadata = null; + List contributingProviders = []; + + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - return; + mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); + contributingProviders.Add(metadataProvider.Name); + // the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely + bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); } catch (Exception) { @@ -215,25 +355,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } - // no metadata provider returned usable metadata, mark the book as failed to enrich - book.MarkMetadataAsFailed(); - await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (mergedMetadata is null) + return null; + + Result applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow); + return applyMetadataResult.IsFailure ? null : mergedMetadata; } /// - /// Determines whether the provided is usable, meaning it has a title and at least one primary identifier. + /// Resolves the artwork of the from the , in their configured order, storing the artwork of the first provider that returns it. /// - /// The metadata to validate. - /// when the metadata is usable, otherwise . - private static bool IsUsableMetadata(BookMetadataDto metadata) + /// The book whose artwork is enriched. + /// The metadata applied to the book, used to build the directory of the book artwork. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The name of the media library the book belongs to. + /// Cancellation token that can be used to stop the execution. + private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, CancellationToken cancellationToken) { - if (string.IsNullOrWhiteSpace(metadata.Title)) - return false; - return !string.IsNullOrWhiteSpace(metadata.GoodreadsId) - || !string.IsNullOrWhiteSpace(metadata.OpenLibraryId) - || !string.IsNullOrWhiteSpace(metadata.GoogleBooksId) - || !string.IsNullOrWhiteSpace(metadata.ASIN) - || (metadata.Isbns is not null && metadata.Isbns.Count > 0); + if (bookArtworkService is null || artworkProviders.Count == 0) + return; + + foreach (IArtworkProvider provider in artworkProviders) + { + ArtworkDto? artwork = null; + try + { + artwork = await provider.GetArtworkAsync(new BookMetadataLookupDto(LibraryId: book.LibraryId.Value, Path: book.Path), cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // a failing artwork provider must not prevent the other providers from being tried + } + + if (artwork is null) + continue; + + // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract + if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) + continue; + + string authorName = appliedMetadata.Contributors?.FirstOrDefault(contributor => contributor.Name?.DisplayName is not null)?.Name?.DisplayName ?? string.Empty; + string bookTitle = appliedMetadata.Title ?? book.Metadata.Title; + Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(book.LibraryId.Value, book.Id.Value, libraryName, authorName, bookTitle, artwork, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + continue; + + book.SetBookCoverImagePath(saveArtworkResult.Value); + return; + } + } + + /// + /// Enriches the with the identifiers and the title discovered by the already queried metadata providers. + /// + /// The lookup to enrich. + /// The metadata discovered by the already queried metadata providers. + /// The enriched lookup. + private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata) + { + string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value; + string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId; + string? title = bookMetadataLookup.Title ?? bookMetadata.Title; + return bookMetadataLookup with + { + Isbn = isbn, + OpenLibraryId = openLibraryId, + Title = title + }; + } + + /// + /// Determines whether the provided is usable, meaning it has a title. + /// + /// The metadata to validate. + /// when the metadata is usable, otherwise . + private static bool IsUsableMetadata(BookMetadataDto bookMetadata) + { + return !string.IsNullOrWhiteSpace(bookMetadata.Title); } /// diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs new file mode 100644 index 00000000..3d314e8b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Merges the book metadata returned by multiple metadata providers into a single book metadata, giving priority to the first provider that provides a value for each field. +/// +internal static class MetadataAggregator +{ + /// + /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields. + /// + /// The first metadata to merge, whose values have priority. + /// The second metadata to merge, filling the fields that the first metadata lacks. + /// The merged metadata. + public static BookMetadataDto Merge(BookMetadataDto first, BookMetadataDto second) + { + return new BookMetadataDto( + FirstOrDefaultReference(first.Title, second.Title), + FirstOrDefaultReference(first.OriginalTitle, second.OriginalTitle), + FirstOrDefaultReference(first.Description, second.Description), + MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo), + Union(first.Genres, second.Genres, genre => genre.Name), + Union(first.Tags, second.Tags, tag => tag.Name), + FirstOrDefaultReference(first.Language, second.Language), + FirstOrDefaultReference(first.OriginalLanguage, second.OriginalLanguage), + FirstOrDefaultReference(first.Publisher, second.Publisher), + FirstOrDefaultValue(first.PageCount, second.PageCount), + FirstOrDefaultValue(first.Format, second.Format), + FirstOrDefaultReference(first.Edition, second.Edition), + FirstOrDefaultValue(first.VolumeNumber, second.VolumeNumber), + FirstOrDefaultReference(first.Series, second.Series), + FirstOrDefaultReference(first.ASIN, second.ASIN), + FirstOrDefaultReference(first.GoodreadsId, second.GoodreadsId), + FirstOrDefaultReference(first.LCCN, second.LCCN), + FirstOrDefaultReference(first.OCLCNumber, second.OCLCNumber), + FirstOrDefaultReference(first.OpenLibraryId, second.OpenLibraryId), + FirstOrDefaultReference(first.LibraryThingId, second.LibraryThingId), + FirstOrDefaultReference(first.GoogleBooksId, second.GoogleBooksId), + FirstOrDefaultReference(first.BarnesAndNobleId, second.BarnesAndNobleId), + FirstOrDefaultReference(first.AppleBooksId, second.AppleBooksId), + Union(first.Isbns, second.Isbns, isbn => isbn.Value), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role?.Name}"), + Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()), + FirstOrDefaultReference(first.CoverImagePath, second.CoverImagePath)); + } + + /// + /// Merges the release information of the two metadata, keeping the first non-null value of each field. + /// + /// The first release information, whose values have priority. + /// The second release information, filling the fields that the first one lacks. + /// The merged release information, or when both are . + private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second) + { + if (first is null && second is null) + return null; + + return new ReleaseInfoDto( + FirstOrDefaultValue(first?.OriginalReleaseDate, second?.OriginalReleaseDate), + FirstOrDefaultValue(first?.OriginalReleaseYear, second?.OriginalReleaseYear), + FirstOrDefaultValue(first?.ReReleaseDate, second?.ReReleaseDate), + FirstOrDefaultValue(first?.ReReleaseYear, second?.ReReleaseYear), + FirstOrDefaultReference(first?.ReleaseCountry, second?.ReleaseCountry), + FirstOrDefaultReference(first?.ReleaseVersion, second?.ReleaseVersion)); + } + + /// + /// Gets the first non-null value of the two reference values. + /// + /// The type of the reference values. + /// The value with priority. + /// The fallback value. + /// The first non-null value, or when both are . + private static T? FirstOrDefaultReference(T? first, T? second) + where T : class + { + return first ?? second; + } + + /// + /// Gets the first non-null value of the two nullable value types. + /// + /// The underlying type of the nullable values. + /// The value with priority. + /// The fallback value. + /// The first non-null value, or when both are . + private static T? FirstOrDefaultValue(T? first, T? second) + where T : struct + { + return first ?? second; + } + + /// + /// Returns the union of the two collections, de-duplicated by the key, keeping the items of the first collection on key conflicts. + /// + /// The type of the collection items. + /// The first collection, whose items have priority. + /// The second collection. + /// The function used to extract the de-duplication key of an item. + /// The union of the two collections, or when both are . + private static List? Union(List? first, List? second, Func keySelector) + where T : class + { + if (first is null && second is null) + return null; + + Dictionary seen = new(StringComparer.OrdinalIgnoreCase); + List result = []; + + void AddRange(List? items) + { + foreach (T item in items ?? []) + if (seen.TryAdd(keySelector(item) ?? string.Empty, item)) + result.Add(item); + } + + AddRange(first); + AddRange(second); + return result; + } +} diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 7790a2e1..6671a6dd 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -1,7 +1,8 @@ { "MediaSettings": { "RootDirectory": "media", - "LibrariesDirectory": "libraries" + "LibrariesDirectory": "libraries", + "BooksDirectory": "books" }, "PluginsSettings": { "Directory": "plugins" diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index 2389d2eb..23cc0cd5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -34,7 +34,7 @@ public class AddLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional."); RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional."); RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); @@ -57,7 +57,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -73,7 +73,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -53,7 +53,7 @@ public class GetLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional."); RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional."); RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); @@ -61,7 +61,7 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -77,7 +77,7 @@ public class UpdateLibraryEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required."); Response(200, "The settings of the current user were successfully updated."); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index bc43dad9..574d7c33 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Library; using System; using System.Collections.Generic; using System.Diagnostics; @@ -56,7 +55,7 @@ public class LibraryDto /// /// Gets or sets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; set; } = true; + public bool CanDownloadMetadataFromWeb { get; set; } = true; /// /// Gets or sets whether this media library should copy the downloaded metadata into the media library content locations, or not. diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index c074a3c6..d38be3b3 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -29,10 +29,15 @@ public class UserSettingsDto /// /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; set; } = true; + + /// + /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; set; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs index 8f00c2dd..73bc9ef4 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs @@ -2,7 +2,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.Libraries; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -29,7 +28,7 @@ public class SaveLibraryEndpointSummary : Summary r.ContentLocations, "The collection of directories that contain the media library files. Required."); RequestParam(r => r.IsEnabled, "Whether the media library is enabled or not. Optional."); RequestParam(r => r.IsLocked, "Whether the media library is locked or not. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether the downloaded metadata should be copied into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether the directories whose contents have not changed since the last scan should be skipped during the scan, or not. Optional."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs index ead45202..bd430938 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.UsersManagement; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -23,7 +22,7 @@ public class UpdateUserSettingsEndpointSummary : Summary r.UserId, "The unique identifier of the user that owns the settings. Optional."); RequestParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Optional."); RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Optional."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional."); ExampleRequest = new UserSettingsDto(); diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 0884bea3..01372ba1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -1,4 +1,4 @@ - +
- : + :
- @_localizer["DescriptionIgnoreThePrefixForAlphaPicker"] + @_localizer["DescriptionShouldIgnoreThePrefixForAlphaPicker"]
@@ -94,8 +94,9 @@ const form = document.getElementById('user-settings-form'); const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled'); const inputItemsPerPage = document.getElementById('ItemsPerPage'); - const checkboxIgnoreThePrefixForAlphaPicker = document.getElementById('IgnoreThePrefixForAlphaPicker'); + const checkboxShouldIgnoreThePrefixForAlphaPicker = document.getElementById('ShouldIgnoreThePrefixForAlphaPicker'); const checkboxIsThemeCachingEnabled = document.getElementById('IsThemeCachingEnabled'); + let shouldAggregateMetadataWhenMissing = false; // toggle the enabled state of the items per page input based on the pagination checkbox function updateItemsPerPageEnabledState() { @@ -108,8 +109,9 @@ if (data) { checkboxIsPaginationEnabled.checked = data.isPaginationEnabled === true; inputItemsPerPage.value = data.itemsPerPage; - checkboxIgnoreThePrefixForAlphaPicker.checked = data.ignoreThePrefixForAlphaPicker === true; + checkboxShouldIgnoreThePrefixForAlphaPicker.checked = data.shouldIgnoreThePrefixForAlphaPicker === true; checkboxIsThemeCachingEnabled.checked = data.isThemeCachingEnabled === true; + shouldAggregateMetadataWhenMissing = data.shouldAggregateMetadataWhenMissing === true; updateItemsPerPageEnabledState(); } } @@ -119,8 +121,9 @@ const formData = { IsPaginationEnabled: checkboxIsPaginationEnabled.checked, ItemsPerPage: Number(inputItemsPerPage.value), - IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked, - IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked + ShouldIgnoreThePrefixForAlphaPicker: checkboxShouldIgnoreThePrefixForAlphaPicker.checked, + IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked, + ShouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs new file mode 100644 index 00000000..ce13ed13 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryContentLocationEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The path of the media library content location. + /// The created . + public LibraryContentLocationEntity Create( + string? path = null) + { + return new LibraryContentLocationEntity + { + Path = path ?? _faker.System.DirectoryPath() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index 605ca97f..deda345c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -27,7 +27,7 @@ public class LibraryEntityFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created media library entity. @@ -40,7 +40,7 @@ public class LibraryEntityFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -56,7 +56,7 @@ public class LibraryEntityFixture LibraryScans = [], IsEnabled = isEnabled, IsLocked = isLocked, - DownloadMetadataFromWeb = downloadMetadataFromWeb, + CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, CreatedOnUtc = default, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs index e43f575f..7af3eb39 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs @@ -21,14 +21,19 @@ public class LibraryMetadataProviderConfigurationEntityFixture /// The Id of the media library the configuration belongs to. /// The Id of the plugin providing the metadata. /// The rank of the metadata provider, determining the order in which providers are tried. + /// Whether the metadata provider is enabled or not. /// The created . - public LibraryMetadataProviderConfigurationEntity Create(Guid libraryId, Guid pluginId, int rank) + public LibraryMetadataProviderConfigurationEntity Create( + Guid libraryId, + Guid pluginId, + int rank, + bool isEnabled = true) { return new Faker() .RuleFor(configuration => configuration.Id, faker => faker.Random.Guid()) .RuleFor(configuration => configuration.LibraryId, libraryId) .RuleFor(configuration => configuration.PluginId, pluginId) - .RuleFor(configuration => configuration.IsEnabled, faker => faker.Random.Bool()) + .RuleFor(configuration => configuration.IsEnabled, isEnabled) .RuleFor(configuration => configuration.Rank, rank) .RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past()) .RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid()) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs index c46f8762..27d9cb12 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs @@ -21,17 +21,26 @@ public class PluginEntityFixture /// Creates a random valid . ///
/// The Id of the plugin, or to generate a random one. + /// The name of the plugin, or to generate a random one. + /// The load status of the plugin, or to generate a random one. + /// The serialized settings of the plugin, or to generate random ones. + /// Whether the settings should be included, or forced to . /// The created . - public PluginEntity Create(Guid? id = null) + public PluginEntity Create( + Guid? id = null, + string? name = null, + PluginLoadStatus? loadStatus = null, + string? settingsJson = null, + bool includeSettingsJson = true) { return new Faker() .RuleFor(plugin => plugin.Id, faker => id ?? faker.Random.Guid()) - .RuleFor(plugin => plugin.Name, faker => faker.Company.CompanyName()) + .RuleFor(plugin => plugin.Name, faker => name ?? faker.Company.CompanyName()) .RuleFor(plugin => plugin.Author, faker => faker.Name.FullName()) .RuleFor(plugin => plugin.Version, faker => faker.System.Semver()) .RuleFor(plugin => plugin.Description, faker => faker.Lorem.Sentence()) - .RuleFor(plugin => plugin.LoadStatus, faker => faker.PickRandom()) - .RuleFor(plugin => plugin.SettingsJson, faker => JsonSerializer.Serialize(new Dictionary { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) })) + .RuleFor(plugin => plugin.LoadStatus, faker => loadStatus ?? faker.PickRandom()) + .RuleFor(plugin => plugin.SettingsJson, faker => includeSettingsJson ? settingsJson ?? JsonSerializer.Serialize(new Dictionary { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) }) : null) .RuleFor(plugin => plugin.CreatedOnUtc, faker => faker.Date.Past()) .RuleFor(plugin => plugin.CreatedBy, faker => faker.Random.Guid()) .RuleFor(plugin => plugin.UpdatedOnUtc, faker => faker.Date.Recent()) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs index e6e86104..d5074175 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs @@ -22,16 +22,18 @@ public class UserSettingsEntityFixture /// Optional. The Id of the user that owns these settings. /// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. - /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. /// Optional. Whether the theme data served to this user is cached, or not. + /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// The created user settings entity. public UserSettingsEntity Create( Guid? id = null, Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null, - bool? isThemeCachingEnabled = null) + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { return new Faker() .CustomInstantiator(f => new UserSettingsEntity @@ -40,8 +42,9 @@ public class UserSettingsEntityFixture UserId = userId ?? Guid.NewGuid(), IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(), ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100), - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool(), - IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool() + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool(), + IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool(), + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? f.Random.Bool() }) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs new file mode 100644 index 00000000..22d42e9a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The root directory where media files are stored. + /// Optional. The directory where media library files are stored. + /// Optional. The directory where the media item files are stored. + /// The created . + public MediaSettingsDto Create( + string? rootDirectory = null, + string? librariesDirectory = null, + string? booksDirectory = null) + { + return new MediaSettingsDto + { + RootDirectory = rootDirectory ?? _faker.System.DirectoryPath(), + LibrariesDirectory = librariesDirectory ?? _faker.System.DirectoryPath(), + BooksDirectory = booksDirectory ?? _faker.System.DirectoryPath() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs index beb7bf52..96e537b3 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -25,7 +24,7 @@ public class AddLibraryCommandFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created command. @@ -36,7 +35,7 @@ public class AddLibraryCommandFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -58,7 +57,7 @@ public class AddLibraryCommandFixture .RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath()) .RuleFor(x => x.IsEnabled, isEnabled) .RuleFor(x => x.IsLocked, isLocked) - .RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb) + .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs index 2bdddac8..284c8d6d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs @@ -27,7 +27,7 @@ public class UpdateLibraryCommandFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created command. @@ -40,7 +40,7 @@ public class UpdateLibraryCommandFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -66,7 +66,7 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath()) .RuleFor(x => x.IsEnabled, isEnabled) .RuleFor(x => x.IsLocked, isLocked) - .RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb) + .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index d26b85c7..26814704 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -19,21 +19,23 @@ public class UpdateUserSettingsCommandFixture ///
/// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. - /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. /// Optional. Whether the theme data served to this user is cached, or not. /// The created command. public UpdateUserSettingsCommand Create( bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null, - bool? isThemeCachingEnabled = null) + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { return new Faker() - .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default)) + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) - .RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool()) + .RuleFor(x => x.ShouldIgnoreThePrefixForAlphaPicker, f => shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool()) .RuleFor(x => x.IsThemeCachingEnabled, f => isThemeCachingEnabled ?? f.Random.Bool()) + .RuleFor(x => x.ShouldAggregateMetadataWhenMissing, f => shouldAggregateMetadataWhenMissing ?? f.Random.Bool()) .Generate(); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index d297d071..b48be3f2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -26,7 +25,7 @@ public class AddLibraryRequestFixture /// Optional. The path of the image file used as the cover. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// The created . @@ -37,7 +36,7 @@ public class AddLibraryRequestFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null) { @@ -48,7 +47,7 @@ public class AddLibraryRequestFixture coverImage ?? null, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index ebdd308b..ca1bd352 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -28,7 +28,7 @@ public class UpdateLibraryRequestFixture /// Optional. The path of the image file used as the cover. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// The created . @@ -41,7 +41,7 @@ public class UpdateLibraryRequestFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null) { @@ -54,7 +54,7 @@ public class UpdateLibraryRequestFixture coverImage ?? null, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs new file mode 100644 index 00000000..f2f99c6f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Whether pagination is enabled for the user. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// The created . + public UpdateUserSettingsRequest Create( + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) + { + return new UpdateUserSettingsRequest( + isPaginationEnabled ?? _faker.Random.Bool(), + itemsPerPage ?? _faker.Random.Int(1, 100), + shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + isThemeCachingEnabled ?? _faker.Random.Bool(), + shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs index c3402218..06493766 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs @@ -29,7 +29,7 @@ public class LibraryResponseFixture /// Optional. The path of the image file used as the cover of the library. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// Optional. The date and time when the library was created. @@ -44,7 +44,7 @@ public class LibraryResponseFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, DateTime? createdOnUtc = null, @@ -59,7 +59,7 @@ public class LibraryResponseFixture coverImage, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs new file mode 100644 index 00000000..7b9e2c5a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the metadata. + /// Optional. The display name of the metadata provider. + /// Optional. Whether the metadata provider is enabled for the media library. + /// Optional. The rank of the metadata provider. + /// The created . + public LibraryMetadataProviderResponse Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryMetadataProviderResponse( + pluginId ?? Guid.NewGuid(), + name ?? _faker.Company.CompanyName(), + isEnabled ?? _faker.Random.Bool(), + rank ?? _faker.Random.Int(1, 100)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs new file mode 100644 index 00000000..7ebc342b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user that owns these settings. + /// Optional. Whether pagination is enabled for the user. + /// Optional. The number of library items displayed per page when pagination is enabled. + /// Optional. Whether the "The" prefix is ignored by the alpha picker. + /// Optional. Whether the theme data served to this user is cached. + /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// The created . + public UserSettingsResponse Create( + Guid? userId = null, + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) + { + return new UserSettingsResponse( + userId ?? Guid.NewGuid(), + isPaginationEnabled ?? _faker.Random.Bool(), + itemsPerPage ?? _faker.Random.Int(1, 100), + shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + isThemeCachingEnabled ?? _faker.Random.Bool(), + shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs index c438f06b..449396f2 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -35,7 +35,7 @@ public class LibraryFixture /// Whether to include a cover image or not. /// Whether the library is enabled. /// Whether the library is locked. - /// Whether metadata download from the web is enabled. + /// Whether metadata download from the web is enabled. /// Whether metadata should be saved in the media directories. /// Whether unchanged directories should be skipped during scan. /// Optional. The scan Ids associated with the library. @@ -50,7 +50,7 @@ public class LibraryFixture bool includeCoverImage = true, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = false, bool shouldSkipUnchangedDirectoriesDuringScan = false, IEnumerable? scanIds = null) @@ -75,7 +75,7 @@ public class LibraryFixture resolvedCoverImage, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, resolvedScanIds @@ -89,7 +89,7 @@ public class LibraryFixture resolvedCoverImage, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, resolvedScanIds diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs index 89134b4e..6f15968e 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -22,22 +22,25 @@ public class UserSettingsFixture /// Optional. The Id of the user that owns the settings. /// Whether pagination is enabled for the user. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker. /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. /// The created . public UserSettings Create( Guid? userId = null, bool isPaginationEnabled = true, int itemsPerPage = 48, - bool ignoreThePrefixForAlphaPicker = false, - bool isThemeCachingEnabled = true) + bool shouldIgnoreThePrefixForAlphaPicker = false, + bool isThemeCachingEnabled = true, + bool shouldAggregateMetadataWhenMissing = false) { Result settings = UserSettings.Create( userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value), isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker, - isThemeCachingEnabled); + shouldIgnoreThePrefixForAlphaPicker, + isThemeCachingEnabled, + shouldAggregateMetadataWhenMissing); return settings.Value; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs index b6a98ac1..bf1d8f30 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -15,6 +15,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; [ExcludeFromCodeCoverage] public class LibraryDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -26,16 +28,15 @@ public class LibraryDtoFixture /// A configured instance. public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List? contentLocations = null) { - Faker faker = new(); return new LibraryDto { Id = id ?? Guid.NewGuid(), UserId = Guid.NewGuid(), - Title = title ?? faker.Commerce.Department(), - LibraryType = libraryType ?? faker.PickRandom("Book", "Video", "Photo"), - CoverImage = faker.Image.PicsumUrl(), - ContentLocations = contentLocations ?? [faker.System.DirectoryPath()], - IsEnabled = isEnabled ?? faker.Random.Bool() + Title = title ?? _faker.Commerce.Department(), + LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"), + CoverImage = _faker.Image.PicsumUrl(), + ContentLocations = contentLocations ?? [_faker.System.DirectoryPath()], + IsEnabled = isEnabled ?? _faker.Random.Bool() }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs new file mode 100644 index 00000000..9a040489 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the media library scan. + /// Optional Id of the scanned media library. + /// A configured instance. + public ScanLibraryDto Create( + Guid? scanId = null, + Guid? libraryId = null) + { + return new ScanLibraryDto + { + ScanId = scanId ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs new file mode 100644 index 00000000..02c24777 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the plugin providing the metadata. + /// Optional display name of the metadata provider. + /// Whether the metadata provider is enabled for the media library or not. + /// Optional rank of the metadata provider, determining the order in which providers are tried. + /// A configured instance. + public LibraryMetadataProviderDto Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryMetadataProviderDto + { + PluginId = pluginId ?? Guid.NewGuid(), + Name = name ?? _faker.Company.CompanyName(), + IsEnabled = isEnabled ?? _faker.Random.Bool(), + Rank = rank ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs new file mode 100644 index 00000000..be62805c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Enums.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingDescriptorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the setting. + /// Optional. The display label of the setting. + /// Optional. The type of the setting. + /// Optional. The default value of the setting. + /// Optional. The list of allowed values of the setting. + /// The created . + public PluginSettingDescriptorDto Create( + string? key = null, + string? label = null, + PluginSettingType? type = null, + string? defaultValue = null, + IReadOnlyList? allowedValues = null) + { + return new PluginSettingDescriptorDto + { + Key = key ?? _faker.Random.String2(4, 32), + Label = label ?? _faker.Commerce.ProductName(), + Type = type ?? _faker.Random.Enum(), + DefaultValue = defaultValue, + AllowedValues = allowedValues + }; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs new file mode 100644 index 00000000..7a06532e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingsDtoFixture +{ + private readonly Faker _faker = new(); + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the plugin. + /// Whether to populate the current settings values, or leave them null. + /// Whether to populate the settings schema, or leave it empty. + /// A configured instance. + public PluginSettingsDto Create( + Guid? pluginId = null, + bool includeSettings = true, + bool includeSchema = true) + { + string settingKey = _faker.Lorem.Word(); + return new PluginSettingsDto + { + PluginId = pluginId ?? Guid.NewGuid(), + Schema = includeSchema + ? [_pluginSettingDescriptorDtoFixture.Create(key: settingKey)] + : [], + Settings = includeSettings + ? new Dictionary { [settingKey] = _faker.Lorem.Word() } + : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs index 74311aa5..6d49a13d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -15,23 +15,34 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; [ExcludeFromCodeCoverage] public class UserSettingsDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional identifier of the user that owns the settings. /// Whether pagination is enabled for the user. /// Number of library items displayed per page. - /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. /// A configured instance. - public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null) + public UserSettingsDto Create( + Guid? userId = null, + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { - Faker faker = new(); return new UserSettingsDto { UserId = userId ?? Guid.NewGuid(), - IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(), - ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200), - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool() + IsPaginationEnabled = isPaginationEnabled ?? _faker.Random.Bool(), + ItemsPerPage = itemsPerPage ?? _faker.Random.Int(1, 200), + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + IsThemeCachingEnabled = isThemeCachingEnabled ?? _faker.Random.Bool(), + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool() }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..18439e07 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional plugin Ids in the new order. + /// A configured instance. + public ReorderLibraryMetadataProvidersRequest Create( + Guid? libraryId = null, + List? pluginIds = null) + { + return new ReorderLibraryMetadataProvidersRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + PluginIds = pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs new file mode 100644 index 00000000..4ee3fa19 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional identifier of the plugin. + /// Optional value indicating whether the metadata provider is enabled. + /// A configured instance. + public SetLibraryMetadataProviderEnabledRequest Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool? isEnabled = null) + { + return new SetLibraryMetadataProviderEnabledRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + PluginId = pluginId ?? Guid.NewGuid(), + IsEnabled = isEnabled ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs index 725afc87..973f54ea 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -15,19 +15,22 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; [ExcludeFromCodeCoverage] public class UpdatePluginSettingsRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional identifier of the plugin. /// Optional dictionary of settings. /// A configured instance. - public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary? settings = null) + public UpdatePluginSettingsRequest Create( + Guid? pluginId = null, + Dictionary? settings = null) { - Faker faker = new(); return new UpdatePluginSettingsRequest { PluginId = pluginId ?? Guid.NewGuid(), - Settings = settings ?? new Dictionary { [faker.Lorem.Word()] = faker.Lorem.Word() } + Settings = settings ?? new Dictionary { [_faker.Lorem.Word()] = _faker.Lorem.Word() } }; } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index 4f54bb96..1c913cff 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -1,8 +1,10 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.Extensions.DependencyInjection; @@ -33,6 +35,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -56,11 +60,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture + /// Seeds a owned by . + ///
+ /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + /// /// Seeds two instances in the database. /// /// The Id of the media library. /// The Id of the first plugin. /// The Id of the second plugin. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginIdA, - IsEnabled = true, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginIdB, - IsEnabled = false, - Rank = 2, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true)); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 6823f24b..c860ca92 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; @@ -10,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -34,6 +32,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -105,36 +104,10 @@ public class GetPluginSettingsEndpointTests : IClassFixture(); - Guid userId = GetCurrentUserId(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); } - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - /// /// Disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index c7f44e09..e71c05ac 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -1,8 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.EntityFrameworkCore; @@ -14,8 +18,6 @@ using System.Linq; 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 @@ -29,6 +31,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -52,15 +57,16 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture + /// Seeds a owned by . + ///
+ /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + /// /// Seeds a in the database. /// /// The Id of the media library. /// The Id of the plugin. - /// The Id of the user that owns the data. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, Guid userId, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginId, - IsEnabled = true, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index d55d16e4..0eb07d2a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -1,23 +1,22 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; -using Lumina.Contracts.Responses.Plugins; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; 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 @@ -31,11 +30,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -59,13 +56,11 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture + /// Seeds a owned by . + ///
+ /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + /// /// Seeds a in the database. /// /// The Id of the media library. /// The Id of the plugin. - /// The Id of the user that owns the data. /// Whether the provider is enabled. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, Guid userId, bool isEnabled, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginId, - IsEnabled = isEnabled, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 38398544..bad7f5b0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; @@ -12,7 +13,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -36,6 +36,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -61,9 +63,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { ["Key1"] = "Value1" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key1"] = "Value1" } ); // Act @@ -85,9 +87,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { ["Key1"] = "Value1" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key1"] = "Value1" } ); // Act @@ -118,36 +120,10 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture(); - Guid userId = GetCurrentUserId(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); } - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - /// /// Disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 50301fd3..1735ed4b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; @@ -27,6 +26,7 @@ public class GetUserSettingsEndpointTests : IClassFixture(); Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; - UserSettingsEntity settings = new() - { - Id = Guid.NewGuid(), - UserId = userId, - IsPaginationEnabled = false, - ItemsPerPage = 24, - IgnoreThePrefixForAlphaPicker = true - }; + UserSettingsEntity settings = _userSettingsEntityFixture.Create( + userId: userId, + isPaginationEnabled: false, + itemsPerPage: 24, + shouldIgnoreThePrefixForAlphaPicker: true); dbContext.UserSettings.Add(settings); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 105106e8..d3a77004 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -28,6 +29,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture + diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..19fa67c2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains integration tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserSettings_WhenCalledByAuthenticatedUser_ShouldReturnSettingsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create(itemsPerPage: 24); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings", expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(24, json.RootElement.GetProperty("data").GetProperty("itemsPerPage").GetInt32()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs new file mode 100644 index 00000000..d5a1c00b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings; + +/// +/// Contains integration tests for the /{culture}/tools/settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SettingsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SettingsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SettingsView_WhenCalledByAuthenticatedUser_ShouldRenderSettingsPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/tools/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("user-settings-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..be26d418 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.Common; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains integration tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledByAuthenticatedUser_ShouldUpdateSettings() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + UserSettingsDto settings = _userSettingsDtoFixture.Create(isThemeCachingEnabled: true); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdateSettingsRequest(settings, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } + + /// + /// Builds the update request that sends the given to the user settings endpoint. + /// + /// The user settings to send. + /// The antiforgery token to include in the request. + /// The configured update request. + private static HttpRequestMessage CreateUpdateSettingsRequest(UserSettingsDto settings, string antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(settings) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index d215cd92..f8467d7e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -1,19 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders; @@ -30,6 +25,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -74,7 +71,7 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -121,23 +108,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture for the library identified by . ///
/// The Id of the media library. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = true, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 0dce62e1..a6f962e6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -1,18 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; @@ -29,6 +24,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -71,8 +67,8 @@ public class GetPluginSettingsEndpointTests : IClassFixture // Arrange // authenticate with an admin user and seed a plugin, so a valid pluginId would reach the handler HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - await SeedPluginAsync(userId); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedPluginAsync(); // Act HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings"); @@ -91,28 +87,14 @@ public class GetPluginSettingsEndpointTests : IClassFixture } /// - /// Seeds a created by . + /// Seeds a created by the authenticated admin user. /// - /// The Id of the creator. /// A task representing the asynchronous operation. - private async Task SeedPluginAsync(Guid userId) + private async Task SeedPluginAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Plugins.Add(new PluginEntity - { - Id = Guid.NewGuid(), - Name = "Test Plugin", - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index 26964523..aa6a983e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -1,21 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; @@ -32,6 +28,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -48,9 +47,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -132,24 +121,13 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture for the library identified by . /// /// The Id of the media library. - /// The Id of the user that owns the data. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = true, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index d25358e1..62ba2bcc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -1,21 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; @@ -32,6 +28,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -49,11 +48,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -134,23 +115,12 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture for the library identified by . ///
/// The Id of the media library. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = false, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 0a63870d..e0b4ebd4 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; @@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; @@ -31,6 +29,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -47,9 +47,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { // Arrange string pluginId = Guid.NewGuid().ToString(); - UpdatePluginSettingsRequest request = new( - PluginId: Guid.NewGuid(), - Settings: new Dictionary { ["Key"] = "Value" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: Guid.NewGuid(), + settings: new Dictionary { ["Key"] = "Value" } ); // Act @@ -76,11 +76,11 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { // Arrange HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid pluginId = await SeedPluginAsync(userId); - UpdatePluginSettingsRequest request = new( - PluginId: pluginId, - Settings: new Dictionary { ["Key"] = maliciousValue } + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid pluginId = await SeedPluginAsync(); + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key"] = maliciousValue } ); // Act @@ -107,29 +107,15 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture } /// - /// Seeds a created by . + /// Seeds a created by the authenticated admin user. /// - /// The Id of the creator. /// The Id of the seeded plugin. - private async Task SeedPluginAsync(Guid userId) + private async Task SeedPluginAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid pluginId = Guid.NewGuid(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = "Test Plugin", - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); return pluginId; } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 9baeba1c..8055436e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -1,16 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; @@ -31,6 +30,8 @@ public class GetUserSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -95,20 +96,12 @@ public class GetUserSettingsEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 45193858..b2dcba4a 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -8,10 +10,8 @@ using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; @@ -32,6 +32,9 @@ public class UpdateUserSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -47,11 +50,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: 48, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 48, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -77,11 +81,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); await CreateAndAuthenticateUserAsync(client); - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: int.MaxValue, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: int.MaxValue, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -100,11 +105,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); await CreateAndAuthenticateUserAsync(client); - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: int.MinValue, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: int.MinValue, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -132,20 +138,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..191e3e59 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains security tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs new file mode 100644 index 00000000..2f45ecdf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings; + +/// +/// Contains security tests for the /{culture}/tools/settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SettingsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SettingsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SettingsView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/settings"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..897dc53a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains security tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(_userSettingsDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(_userSettingsDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index 95c91ab8..f3971046 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +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; @@ -14,20 +15,22 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class AddMediaLibraryRequestMappingTests { + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - AddLibraryRequest request = new( - "My Library", - "Book", - ["C:/Books", "D:/Media/Books"], - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -41,7 +44,7 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } @@ -53,16 +56,16 @@ public class AddMediaLibraryRequestMappingTests public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - AddLibraryRequest request = new( - "My Library", - libraryType.ToString(), - ["C:/Media"], - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: libraryType.ToString(), + contentLocations: ["C:/Media"], + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -76,7 +79,7 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } @@ -92,16 +95,16 @@ public class AddMediaLibraryRequestMappingTests "F:/Reading Material" ]; - AddLibraryRequest request = new( - "My Library", - "Book", - contentLocations, - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: contentLocations, + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -122,16 +125,16 @@ public class AddMediaLibraryRequestMappingTests "D:/Books" ]; - AddLibraryRequest request = new( - "My Library", - "Book", - contentLocations, - null, - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: contentLocations, + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs index 455d609d..44bf69ac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== 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.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -17,28 +17,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class LibraryEntityMappingTests { + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly() { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = - [ - new() { Path = "C:/Books" }, - new() { Path = "D:/Media/Books" } - ], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null, - LibraryScans = [] - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -63,19 +52,11 @@ public class LibraryEntityMappingTests public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = libraryType, - ContentLocations = [new() { Path = "C:/Media" }], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: libraryType, + contentLocations: ["C:/Media"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -89,25 +70,11 @@ public class LibraryEntityMappingTests public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly() { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = - [ - new() { Path = "C:/Media/Books" }, - new() { Path = "D:/Books" }, - new() { Path = "E:/Digital Library/Books" }, - new() { Path = "F:/Reading Material" } - ], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Media/Books", "D:/Books", "E:/Digital Library/Books", "F:/Reading Material"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -122,19 +89,12 @@ public class LibraryEntityMappingTests { // Arrange DateTime updated = DateTime.UtcNow.AddDays(-1); - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = [new() { Path = "C:/Books" }], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = updated, - UpdatedBy = Guid.NewGuid() - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + coverImage: "D:/myPoster.jpg"); + entity.UpdatedOnUtc = updated; // Act LibraryResponse result = entity.ToResponse(); @@ -149,19 +109,12 @@ public class LibraryEntityMappingTests { // Arrange DateTime updated = DateTime.UtcNow.AddDays(-1); - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = [new() { Path = "C:/Books" }], - CoverImage = null, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = updated, - UpdatedBy = Guid.NewGuid() - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"]); + entity.CoverImage = null; + entity.UpdatedOnUtc = updated; // Act LibraryResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 0a340076..28e95ff7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; 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.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -34,7 +33,7 @@ public class LibraryMappingTests coverImage: "D:/myPoster.jpg", isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, scanIds: [Guid.NewGuid()]); @@ -54,7 +53,7 @@ public class LibraryMappingTests Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMetadataFromWeb); + Assert.True(result.CanDownloadMetadataFromWeb); Assert.False(result.ShouldSaveMetadataInMediaDirectories); Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id)); } @@ -93,7 +92,7 @@ public class LibraryMappingTests coverImage: "D:/myPoster.jpg", isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false); // Act @@ -105,7 +104,7 @@ public class LibraryMappingTests Assert.Equal(library.CoverImage, result.CoverImage); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMetadataFromWeb); + Assert.True(result.CanDownloadMetadataFromWeb); Assert.False(result.ShouldSaveMetadataInMediaDirectories); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs index 3a7aa785..0e8ec644 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using System.Diagnostics.CodeAnalysis; #endregion @@ -13,11 +14,19 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; [ExcludeFromCodeCoverage] public class UpdateUserSettingsRequestMappingTests { + private readonly UpdateUserSettingsRequestFixture _requestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false, IsThemeCachingEnabled: true); + UpdateUserSettingsRequest request = _requestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 48, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act UpdateUserSettingsCommand result = request.ToCommand(); @@ -26,7 +35,7 @@ public class UpdateUserSettingsRequestMappingTests Assert.NotNull(result); Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(request.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs index f87c367b..de7f9d33 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs @@ -33,7 +33,7 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.UserId, result.Value.UserId.Value); Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage); - Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled); } @@ -51,7 +51,7 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.UserId, result.UserId); Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs index a9241202..4694e62f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs @@ -34,7 +34,7 @@ public class UserSettingsMappingTests Assert.Equal(userId, result.UserId); Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] @@ -52,6 +52,6 @@ public class UserSettingsMappingTests Assert.Equal(userId, result.UserId); Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index 5d0e1272..a26e0808 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -2,17 +2,22 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics.CodeAnalysis; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; @@ -25,8 +30,13 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); + private readonly Guid _userId; /// /// Initializes a new instance of the class. @@ -36,10 +46,18 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); _mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, _mockValidator); + _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -47,16 +65,15 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntityFixture configurationFixture = new(); - LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryMetadataProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) .Returns(new List { firstProvider, secondProvider }); _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -76,7 +93,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [Guid.NewGuid()]), CancellationToken.None); + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -85,4 +102,42 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index c0a5a097..2fa3c5a7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -2,16 +2,22 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics.CodeAnalysis; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; @@ -24,8 +30,17 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; + private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Fixture for generating test data. + /// + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -35,10 +50,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); _mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, _mockValidator); + _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -55,7 +78,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -68,24 +91,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() { // Arrange - LibraryMetadataProviderConfigurationEntity existingConfiguration = new() - { - Id = Guid.NewGuid(), - LibraryId = Guid.NewGuid(), - PluginId = Guid.NewGuid(), - IsEnabled = false, - Rank = 2, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = default, - UpdatedBy = default - }; + LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.Create( + libraryId: Guid.NewGuid(), + pluginId: Guid.NewGuid(), + rank: 2, + isEnabled: false); _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) .Returns(existingConfiguration); _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -103,7 +120,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -112,4 +129,43 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index 7f172a0d..d2b3ee7e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -3,14 +3,15 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Application.Fixtures.Core.Plugins.Commands.UpdatePluginSettings; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings; @@ -25,6 +26,7 @@ public class UpdatePluginSettingsCommandHandlerTests private readonly IPluginRepository _mockPluginRepository; private readonly IValidator _mockValidator; private readonly UpdatePluginSettingsCommandHandler _sut; + private readonly UpdatePluginSettingsCommandFixture _updatePluginSettingsCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -50,7 +52,7 @@ public class UpdatePluginSettingsCommandHandlerTests .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + Result result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -67,7 +69,7 @@ public class UpdatePluginSettingsCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + Result result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs index 774a02f9..d2bb4a86 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs @@ -2,10 +2,15 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -13,6 +18,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataProviders; @@ -26,10 +32,14 @@ public class GetLibraryMetadataProvidersQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockLibraryMetadataProviderConfigurationRepository; private readonly IPluginRepository _mockPluginRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; private readonly GetLibraryMetadataProvidersQueryHandler _sut; private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly Guid _userId; /// /// Initializes a new instance of the class. @@ -41,8 +51,34 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _mockPluginRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); - _sut = new GetLibraryMetadataProvidersQueryHandler(_mockUnitOfWork); + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -155,4 +191,41 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); + await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..19a19dae --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersQueryValidatorTests +{ + private readonly GetLibraryMetadataProvidersQueryValidator _validator = new(); + private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + query = query with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs index 00e7f486..db3a2b55 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs @@ -3,15 +3,15 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; -using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; -using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings; using NSubstitute; using System; using System.Collections.Generic; @@ -33,9 +33,11 @@ public class GetPluginSettingsQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; private readonly IPluginManager _mockPluginManager; + private readonly IValidator _mockValidator; private readonly GetPluginSettingsQueryHandler _sut; private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -46,8 +48,26 @@ public class GetPluginSettingsQueryHandlerTests _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockPluginManager = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager); + _sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPluginIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Plugins.PluginIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError); + await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -62,8 +82,8 @@ public class GetPluginSettingsQueryHandlerTests IPlugin loadedPlugin = Substitute.For(); loadedPlugin.GetSettingsSchema().Returns( [ - new PluginSettingDescriptorDto("key1", "Label 1", PluginSettingType.Text, "default"), - new PluginSettingDescriptorDto("key2", "Label 2", PluginSettingType.Select, null, ["a", "b"]) + _pluginSettingDescriptorDtoFixture.Create(key: "key1", label: "Label 1", type: PluginSettingType.Text, defaultValue: "default"), + _pluginSettingDescriptorDtoFixture.Create(key: "key2", label: "Label 2", type: PluginSettingType.Select, allowedValues: ["a", "b"]) ]); _mockPluginManager.GetPlugin(query.PluginId).Returns(loadedPlugin); IReadOnlyDictionary? expectedSettings = JsonSerializer.Deserialize>(plugin.SettingsJson!); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs new file mode 100644 index 00000000..592d5cbb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsQueryValidatorTests +{ + private readonly GetPluginSettingsQueryValidator _validator = new(); + private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new(); + + [Fact] + public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + query = query with { PluginId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index f33a2666..9085a131 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -74,7 +74,7 @@ public class UpdateUserSettingsCommandHandlerTests settings.UserId == _userId && settings.IsPaginationEnabled == command.IsPaginationEnabled && settings.ItemsPerPage == command.ItemsPerPage && - settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -102,7 +102,7 @@ public class UpdateUserSettingsCommandHandlerTests settings.UserId == _userId && settings.IsPaginationEnabled == command.IsPaginationEnabled && settings.ItemsPerPage == command.ItemsPerPage && - settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs index ce16f758..81ce23ea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -28,6 +29,7 @@ public class GetUserSettingsQueryHandlerTests private readonly IUserSettingsRepository _mockUserSettingsRepository; private readonly GetUserSettingsQueryHandler _sut; private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly GetUserSettingsQueryFixture _getUserSettingsQueryFixture = new(); private readonly Guid _userId = Guid.NewGuid(); /// @@ -49,7 +51,7 @@ public class GetUserSettingsQueryHandlerTests public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(Result.From(storedSettings)); @@ -62,14 +64,14 @@ public class GetUserSettingsQueryHandlerTests Assert.Equal(storedSettings.UserId, result.Value.UserId); Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage); - Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(Result.From(null)); @@ -81,14 +83,14 @@ public class GetUserSettingsQueryHandlerTests Assert.NotEqual(Guid.Empty, result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -104,7 +106,7 @@ public class GetUserSettingsQueryHandlerTests public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index feec240b..1aad9a82 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -43,5 +43,6 @@ + diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs index 69278ec0..11e0ea34 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class AddLibraryRequestTests { + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -21,16 +23,16 @@ public class AddLibraryRequestTests public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues() { // Arrange - AddLibraryRequest expected = new( - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + AddLibraryRequest expected = _addLibraryRequestFixture.Create( + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -45,20 +47,20 @@ public class AddLibraryRequestTests public void Deconstruct_WhenCalled_ShouldReturnAllProperties() { // Arrange - AddLibraryRequest sut = new( - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + AddLibraryRequest sut = _addLibraryRequestFixture.Create( + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act - (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; // Assert Assert.Equal(sut.Title, title); @@ -67,7 +69,7 @@ public class AddLibraryRequestTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs index ae55cab5..f384abee 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using System; using System.Diagnostics.CodeAnalysis; @@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class UpdateLibraryRequestTests { + private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -24,18 +26,18 @@ public class UpdateLibraryRequestTests // Arrange Guid id = Guid.NewGuid(); Guid userId = Guid.NewGuid(); - UpdateLibraryRequest expected = new( - id, - userId, - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + UpdateLibraryRequest expected = _updateLibraryRequestFixture.Create( + id: id, + userId: userId, + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -52,22 +54,22 @@ public class UpdateLibraryRequestTests // Arrange Guid id = Guid.NewGuid(); Guid userId = Guid.NewGuid(); - UpdateLibraryRequest sut = new( - id, - userId, - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + UpdateLibraryRequest sut = _updateLibraryRequestFixture.Create( + id: id, + userId: userId, + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act - (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; // Assert Assert.Equal(sut.Id, sutId); @@ -78,7 +80,7 @@ public class UpdateLibraryRequestTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs index a8b6cbfc..4b8e2d6a 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings; [ExcludeFromCodeCoverage] public class UpdateUserSettingsRequestTests { + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -21,7 +23,13 @@ public class UpdateUserSettingsRequestTests public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues() { // Arrange - UpdateUserSettingsRequest expected = new(true, 50, true, true); + UpdateUserSettingsRequest expected = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 50, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -36,15 +44,22 @@ public class UpdateUserSettingsRequestTests public void Deconstruct_WhenCalled_ShouldReturnAllProperties() { // Arrange - UpdateUserSettingsRequest sut = new(false, 25, false, false); + UpdateUserSettingsRequest sut = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: false, + itemsPerPage: 25, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: false, + shouldAggregateMetadataWhenMissing: false + ); // Act - (bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; + (bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut; // Assert Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); + Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs index 601c64db..38d65cd1 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs @@ -58,7 +58,7 @@ public class LibraryResponseTests LibraryResponse sut = _libraryResponseFixture.Create(); // Act - (Guid id, Guid userId, string title, LibraryType libraryType, List contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut; + (Guid id, Guid userId, string title, LibraryType libraryType, List contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut; // Assert Assert.Equal(sut.Id, id); @@ -69,7 +69,7 @@ public class LibraryResponseTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); Assert.Equal(sut.CreatedOnUtc, createdOnUtc); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs index 0bd9c3ff..a7d884c0 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; using Lumina.Contracts.Responses.UsersManagement.Settings; using System; using System.Diagnostics.CodeAnalysis; @@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings; [ExcludeFromCodeCoverage] public class UserSettingsResponseTests { + private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -23,7 +25,14 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse expected = new(userId, true, 50, true, true); + UserSettingsResponse expected = _userSettingsResponseFixture.Create( + userId: userId, + isPaginationEnabled: true, + itemsPerPage: 50, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -39,16 +48,24 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse sut = new(userId, false, 25, false, false); + UserSettingsResponse sut = _userSettingsResponseFixture.Create( + userId: userId, + isPaginationEnabled: false, + itemsPerPage: 25, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: false, + shouldAggregateMetadataWhenMissing: false + ); // Act - (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; + (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut; // Assert Assert.Equal(sut.UserId, sutUserId); Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); + Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs index 0cade107..4fc59370 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -53,7 +53,7 @@ public class LibraryConfigurationTests IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title)); IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType)); IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled)); - IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.DownloadMetadataFromWeb)); + IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb)); // Assert Assert.False(titleProperty.IsNullable); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs index 2a7cec99..1638dcb9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs @@ -52,7 +52,7 @@ public class UserSettingsConfigurationTests IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId)); IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled)); IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage)); - IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.IgnoreThePrefixForAlphaPicker)); + IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker)); // Assert Assert.False(userIdProperty.IsNullable); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index f3a7b9b9..1847e96d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -4,7 +4,10 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; @@ -32,6 +35,13 @@ public class BookRepositoryTests private readonly LuminaDbContext _mockContext; private readonly BookRepository _sut; private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); + private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -83,12 +93,12 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() { // Arrange - TagEntity existingTag = new("Existing"); + TagEntity existingTag = _tagEntityFixture.Create(name: "Existing"); _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); BookEntity bookModel = _bookEntityFixture.Create(); - bookModel.Tags = [new("Existing"), new("New")]; + bookModel.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")]; // Act Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -110,12 +120,12 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes() { // Arrange - GenreEntity existingGenre = new("Existing"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing"); _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); BookEntity bookModel = _bookEntityFixture.Create(); - bookModel.Genres = [new("Existing"), new("New")]; + bookModel.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")]; // Act Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -168,9 +178,9 @@ public class BookRepositoryTests { // Arrange BookEntity book = _bookEntityFixture.Create(); - book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; - book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; - book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; + book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -341,8 +351,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -360,8 +370,8 @@ public class BookRepositoryTests public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() { // Arrange - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - BaseFilterDto filter = new(); + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + BaseFilterDto filter = _baseFilterDtoFixture.Create(); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -375,8 +385,8 @@ public class BookRepositoryTests public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() { // Arrange - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = Guid.Empty }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -397,7 +407,7 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - LibraryFilterDto filter = new() { LibraryId = libraryId }; + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None); @@ -425,8 +435,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(fellowshipBook, towersBook); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship"); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -449,8 +459,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 2 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -478,8 +488,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(bookA, bookB); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None); @@ -496,15 +506,15 @@ public class BookRepositoryTests Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); book.LibraryId = libraryId; - book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; - book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; - book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; - book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)]; + book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; + book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs index fe5586a3..fc94cdc6 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; @@ -23,6 +23,7 @@ public class LuminaDbContextTests : IDisposable private readonly string _connectionString; private readonly SqliteConnection _anchorConnection; private readonly LuminaDbContext _context; + private readonly BookEntityFixture _bookEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +47,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(24, tableNames.Length); + Assert.Equal(25, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -63,6 +64,7 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("DirectoryScanFingerprints", tableNames); Assert.Contains("Plugins", tableNames); Assert.Contains("LibraryMetadataProviderConfigurations", tableNames); + Assert.Contains("LibraryArtworkProviderConfigurations", tableNames); Assert.Contains("Tags", tableNames); Assert.Contains("Genres", tableNames); Assert.Contains("LibraryContentLocations", tableNames); @@ -78,17 +80,10 @@ public class LuminaDbContextTests : IDisposable { // Arrange _context.Database.EnsureCreated(); - BookEntity book = new() - { - Id = Guid.NewGuid(), - LibraryId = Guid.NewGuid(), - Path = "/books/test.epub", - Title = "Test Book", - MetadataStatus = MetadataStatus.Pending, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedBy = null - }; + BookEntity book = _bookEntityFixture.Create(path: "/books/test.epub", title: "Test Book", includeMetadata: false); + book.MetadataStatus = MetadataStatus.Pending; + book.CreatedOnUtc = DateTime.UtcNow; + book.CreatedBy = Guid.NewGuid(); _context.Books.Add(book); // Act diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 1a7a4780..928ae81d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -1,11 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; @@ -100,6 +96,26 @@ public class UnitOfWorkTests await dbContext.Received(1).SaveChangesAsync(cancellationToken); } + [Fact] + public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities() + { + // Arrange + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; + LuminaDbContext dbContext = new(options); + UnitOfWork unitOfWork = new(dbContext); + dbContext.Roles.Add(new RoleEntity { Id = Guid.NewGuid(), RoleName = "TestRole" }); + await dbContext.SaveChangesAsync(CancellationToken.None); + Assert.NotEmpty(dbContext.ChangeTracker.Entries()); + + // Act + unitOfWork.ClearTrackedEntities(); + + // Assert + Assert.Empty(dbContext.ChangeTracker.Entries()); + } + [Fact] public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index 82cede13..ca069f9b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -3,7 +3,6 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -14,7 +13,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -50,7 +48,7 @@ public class LibraryTests coverImageSourcePath, isEnabled: false, isLocked: true, - downloadMetadataFromWeb: false, + canDownloadMetadataFromWeb: false, shouldSaveMetadataInMediaDirectories: true, shouldSkipUnchangedDirectoriesDuringScan: true, scanIds); @@ -64,7 +62,7 @@ public class LibraryTests Assert.Equal(coverImageSourcePath, result.Value.CoverImage); Assert.False(result.Value.IsEnabled); Assert.True(result.Value.IsLocked); - Assert.False(result.Value.DownloadMetadataFromWeb); + Assert.False(result.Value.CanDownloadMetadataFromWeb); Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories); Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan); Assert.Equal(scanIds, result.Value.ScanIds); @@ -87,7 +85,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, scanIds); @@ -109,7 +107,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, []); @@ -136,7 +134,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, []); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index d1abc2cf..ac6ebbdc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -5,7 +5,6 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -34,7 +33,8 @@ public class UserSettingsTests Assert.Equal(userId, result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -48,7 +48,8 @@ public class UserSettingsTests Assert.NotNull(result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -72,15 +73,16 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true); // Assert Assert.False(result.IsFailure); Assert.Equal(userId, result.Value.UserId); Assert.False(result.Value.IsPaginationEnabled); Assert.Equal(24, result.Value.ItemsPerPage); - Assert.True(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.True(result.Value.ShouldIgnoreThePrefixForAlphaPicker); Assert.True(result.Value.IsThemeCachingEnabled); + Assert.True(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -106,7 +108,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); // Assert Assert.True(result.IsFailure); @@ -120,14 +122,15 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true); // Assert Assert.False(result.IsFailure); Assert.False(userSettings.IsPaginationEnabled); Assert.Equal(12, userSettings.ItemsPerPage); - Assert.True(userSettings.IgnoreThePrefixForAlphaPicker); + Assert.True(userSettings.ShouldIgnoreThePrefixForAlphaPicker); Assert.False(userSettings.IsThemeCachingEnabled); + Assert.True(userSettings.ShouldAggregateMetadataWhenMissing); } [Theory] @@ -139,7 +142,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index 63877702..fab2baae 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -1,9 +1,22 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -13,14 +26,17 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -45,6 +61,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -106,6 +129,51 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockUnitOfWork.Received(1).ClearTrackedEntities(); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { @@ -139,4 +207,371 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + IMetadataProvider secondProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description")); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + // the book has no known identifiers of its own, so the findings of the first provider are fed to the second one + book.OpenLibraryId = null; + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the second provider receives the lookup enriched with the open library Id discovered by the first provider + await secondProvider.Received(1).GetMetadataAsync( + Arg.Is(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"), + Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + IMetadataProvider secondProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata + await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1) + ])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockBookRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Failed), + Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get the artwork provider configurations")); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid artworkPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(artworkPluginId, artworkProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + using ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.Received(1).SaveBookArtworkAsync( + _libraryId.Value, + book.Id, + Arg.Any(), + Arg.Any(), + "First Title", + Arg.Any(), + Arg.Any()); + await _mockBookRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid webPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + IMetadataProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); + + SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId, webPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched + await localProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid webPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + IMetadataProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); + + SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId, webPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the provider requiring access to the web is used when the library permits downloading data from the web + await webProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid artworkPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Local Title")); + + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Web Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.RequiresWebAccess.Returns(true); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + ServiceCollection services = new(); + services.AddKeyedSingleton(localPluginId, localProvider); + services.AddKeyedSingleton(artworkPluginId, artworkProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + using ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web + await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + /// + /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. + /// + /// The Id of the plugin providing the first metadata provider. + /// The first metadata provider to resolve. + /// The Id of the plugin providing the second metadata provider, if any. + /// The second metadata provider to resolve, if any. + /// Whether the user settings enable aggregating metadata from multiple providers when fields are missing. + private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false) + { + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + if (secondPluginId is not null && secondProvider is not null) + services.AddKeyedSingleton(secondPluginId.Value, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + } + + /// + /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers. + /// + /// The book the job must enrich. + /// The Ids of the plugins configured as metadata providers for the library. + private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds) + { + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>( + configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList())); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs new file mode 100644 index 00000000..59a554c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs @@ -0,0 +1,332 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MetadataAggregatorTests +{ + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, + title: "First Title", + originalTitle: "First Original Title", + description: "First Description", + publisher: "First Publisher", + pageCount: 100, + format: BookFormat.Hardcover, + edition: "First Edition", + volumeNumber: 1, + asin: "FIRST-ASIN", + goodreadsId: "FIRST-GOODREADS", + lccn: "FIRST-LCCN", + oclcNumber: "FIRST-OCLC", + openLibraryId: "FIRST-OL", + libraryThingId: "FIRST-LT", + googleBooksId: "FIRST-GOOGLE", + barnesAndNobleId: "FIRST-BN", + appleBooksId: "FIRST-APPLE", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, + title: "Second Title", + originalTitle: "Second Original Title", + description: "Second Description", + publisher: "Second Publisher", + pageCount: 200, + format: BookFormat.Paperback, + edition: "Second Edition", + volumeNumber: 2, + asin: "SECOND-ASIN", + goodreadsId: "SECOND-GOODREADS", + lccn: "SECOND-LCCN", + oclcNumber: "SECOND-OCLC", + openLibraryId: "SECOND-OL", + libraryThingId: "SECOND-LT", + googleBooksId: "SECOND-GOOGLE", + barnesAndNobleId: "SECOND-BN", + appleBooksId: "SECOND-APPLE", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First Title", result.Title); + Assert.Equal("First Original Title", result.OriginalTitle); + Assert.Equal("First Description", result.Description); + Assert.Equal("First Publisher", result.Publisher); + Assert.Equal(100, result.PageCount); + Assert.Equal(BookFormat.Hardcover, result.Format); + Assert.Equal("First Edition", result.Edition); + Assert.Equal(1, result.VolumeNumber); + Assert.Equal("FIRST-ASIN", result.ASIN); + Assert.Equal("FIRST-GOODREADS", result.GoodreadsId); + Assert.Equal("FIRST-LCCN", result.LCCN); + Assert.Equal("FIRST-OCLC", result.OCLCNumber); + Assert.Equal("FIRST-OL", result.OpenLibraryId); + Assert.Equal("FIRST-LT", result.LibraryThingId); + Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId); + Assert.Equal("FIRST-BN", result.BarnesAndNobleId); + Assert.Equal("FIRST-APPLE", result.AppleBooksId); + Assert.Equal("First Cover", result.CoverImagePath); + } + + [Fact] + public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, description: null, publisher: null, pageCount: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: "Second Title", description: "Second Description", publisher: "Second Publisher", pageCount: 200); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Second Title", result.Title); + Assert.Equal("Second Description", result.Description); + Assert.Equal("Second Publisher", result.Publisher); + Assert.Equal(200, result.PageCount); + } + + [Fact] + public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Description); + Assert.Null(result.Publisher); + Assert.Null(result.PageCount); + Assert.Null(result.Format); + Assert.Null(result.Edition); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Series); + } + + [Fact] + public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); + first = first with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: "US") }; + second = second with { ReleaseInfo = _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: "UK", releaseVersion: "2.0") }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear); + Assert.Equal("US", result.ReleaseInfo.ReleaseCountry); + Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion); + } + + [Fact] + public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001) }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + } + + [Fact] + public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Genres!.Count); + Assert.Contains(result.Genres, genre => genre.Name == "Science fiction"); + Assert.Contains(result.Genres, genre => genre.Name == "Space opera"); + Assert.Contains(result.Genres, genre => genre.Name == "Fantasy"); + } + + [Fact] + public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Tags!.Count); + Assert.Contains(result.Tags, tag => tag.Name == "Tag A"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag B"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag C"); + } + + [Fact] + public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Isbns!.Count); + Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157"); + Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152"); + } + + [Fact] + public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author"), _mediaContributorDtoFixture.Create("Translator B", "Translator")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A"); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B"); + } + + [Fact] + public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Ratings!.Count); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary); + } + + [Fact] + public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A")], Genres = [_genreDtoFixture.Create(name: "Genre A")], Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag A", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre A", Assert.Single(result.Genres!).Name); + Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag B")], Genres = [_genreDtoFixture.Create(name: "Genre B")], Isbns = [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], Contributors = [_mediaContributorDtoFixture.Create("Author B", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag B", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre B", Assert.Single(result.Genres!).Name); + Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Genres); + Assert.Null(result.Tags); + Assert.Null(result.Isbns); + Assert.Null(result.Contributors); + Assert.Null(result.Ratings); + } + + [Fact] + public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English") }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch") }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("en", result.Language!.LanguageCode); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 0f818641..ffb0928d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -43,6 +43,7 @@ + diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index 84542ef6..8dd41075 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; @@ -28,6 +29,7 @@ public class GetLibraryMetadataProvidersEndpointTests private readonly IQueryHandler>> _mockHandler; private readonly GetLibraryMetadataProvidersEndpoint _sut; private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -46,8 +48,8 @@ public class GetLibraryMetadataProvidersEndpointTests CancellationToken cancellationToken = CancellationToken.None; IReadOnlyList expectedResponses = [ - new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider A", true, 1), - new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider B", false, 2) + _libraryMetadataProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1), + _libraryMetadataProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponses)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index d91e3728..6277cfcb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; using Lumina.Contracts.Requests.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; @@ -27,6 +28,7 @@ public class GetPluginSettingsEndpointTests private readonly IQueryHandler> _mockHandler; private readonly GetPluginSettingsEndpoint _sut; private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new(); + private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,10 +45,10 @@ public class GetPluginSettingsEndpointTests // Arrange GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PluginSettingsResponse expectedResponse = new( - PluginId: request.PluginId, - Schema: [], - Settings: null + PluginSettingsResponse expectedResponse = _pluginSettingsResponseFixture.Create( + pluginId: request.PluginId, + schema: [], + settings: null ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -92,7 +94,7 @@ public class GetPluginSettingsEndpointTests GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new PluginSettingsResponse(request.PluginId, [], null))); + .Returns(Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +120,7 @@ public class GetPluginSettingsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new PluginSettingsResponse(request.PluginId, [], null)); + return Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 190e76d7..b5f947be 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings; @@ -24,6 +25,7 @@ public class GetUserSettingsEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetUserSettingsEndpoint _sut; + private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -39,7 +41,7 @@ public class GetUserSettingsEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false, true); + UserSettingsResponse expectedResponse = _userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -79,7 +81,7 @@ public class GetUserSettingsEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true))); + .Returns(Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false))); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); @@ -104,7 +106,7 @@ public class GetUserSettingsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true)); + return Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false)); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 5e15bdf4..b4054779 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; @@ -23,6 +24,7 @@ public class UpdateUserSettingsEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly UpdateUserSettingsEndpoint _sut; + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -37,7 +39,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker() { // Arrange - UpdateUserSettingsRequest request = new(true, 48, false, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -54,7 +56,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - UpdateUserSettingsRequest request = new(true, 0, false, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -76,7 +78,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler() { // Arrange - UpdateUserSettingsRequest request = new(true, 24, true, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -89,7 +91,7 @@ public class UpdateUserSettingsEndpointTests Arg.Is(command => command.IsPaginationEnabled == request.IsPaginationEnabled && command.ItemsPerPage == request.ItemsPerPage && - command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker && + command.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker && command.IsThemeCachingEnabled == request.IsThemeCachingEnabled), Arg.Is(cancellationToken)); } @@ -112,7 +114,7 @@ public class UpdateUserSettingsEndpointTests }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false, true), cts.Token); + Task operationTask = _sut.ExecuteAsync(_updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 0edb17c5..e734623c 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -38,6 +38,10 @@ public class UpdateUserSettingsEndpointTests _sut = Factory.Create(_mockApiHttpClient, CreateThemeCachePreferenceService()); } + /// + /// Creates a backed by an in-memory hybrid cache. + /// + /// The created theme cache preference service. private static ThemeCachePreferenceService CreateThemeCachePreferenceService() { ServiceCollection services = new(); @@ -50,15 +54,15 @@ public class UpdateUserSettingsEndpointTests { // Arrange UserSettingsDto request = _userSettingsDtoFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutAsync( ApiRoutes.Users.UPDATE_USER_SETTINGS, Arg.Is(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled), Arg.Any()); From 942db4c90ecab4bb15bc40598f07550c086ed32a Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:18:49 -0700 Subject: [PATCH 4/7] Fixes path segment sanitization allowing path separators --- .../DomainLayerServices.cs | 16 +- .../Errors/Errors.FileSystemManagement.cs | 1 + .../Services/IPathService.cs | 7 + .../Services/PathService.cs | 49 ++++ .../Strategies/Path/IPathStrategy.cs | 8 +- .../Strategies/Path/UnixPathStrategy.cs | 9 + .../Strategies/Path/WindowsPathStrategy.cs | 13 +- .../Core/Themes/ThemeService.cs | 33 ++- .../Services/PathServiceTests.cs | 237 ++++++++++++++++++ .../Strategies/Path/UnixPathStrategyTests.cs | 34 +++ .../Path/WindowsPathStrategyTests.cs | 33 +++ .../Core/Themes/ThemeServiceTests.cs | 47 ++-- 12 files changed, 442 insertions(+), 45 deletions(-) diff --git a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs index e8d2dfaa..a12a72a1 100644 --- a/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs +++ b/src/Lumina.Domain/Common/DependencyInjection/DomainLayerServices.cs @@ -35,16 +35,16 @@ public static class DomainLayerServices services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs index 6b099e31..33a9737d 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.FileSystemManagement.cs @@ -29,5 +29,6 @@ public static partial class Errors public static Error FileAlreadyExists => Error.Conflict(description: nameof(FileAlreadyExists)); public static Error DirectoryNotFound => Error.NotFound(description: nameof(DirectoryNotFound)); public static Error DirectoryAlreadyExists => Error.Conflict(description: nameof(DirectoryAlreadyExists)); + public static Error FileTooLarge => Error.Validation(description: nameof(FileTooLarge)); } } diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs index 93a314a4..34a03dab 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/IPathService.cs @@ -59,6 +59,13 @@ public interface IPathService /// A collection of characters that are invalid in the context of paths. char[] GetInvalidPathCharsForPlatform(); + /// + /// Sanitizes a human-readable into a safe path segment. + /// + /// The human-readable name to sanitize. + /// An containing the sanitized path segment, or an error. + Result SanitizeSegment(string name); + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs index d36e1873..02dadc41 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathService.cs @@ -3,7 +3,9 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using System; using System.Collections.Generic; +using System.Linq; #endregion namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -13,6 +15,8 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// public class PathService : IPathService { + private const int MAX_DIRECTORY_SEGMENT_LENGTH = 100; + private readonly IPlatformContext _platformContext; /// @@ -110,6 +114,51 @@ public class PathService : IPathService return _platformContext.PathStrategy.GetInvalidPathCharsForPlatform(); } + /// + /// Sanitizes a human-readable into a safe path segment, replacing the characters that are invalid for the current platform, and rejecting the segments that could escape the directory. + /// + /// The human-readable name to sanitize. + /// An containing the sanitized path segment, or an error. + public Result SanitizeSegment(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return Errors.FileSystemManagement.NameCannotBeEmpty; + + char[] invalidChars = _platformContext.PathStrategy.GetInvalidPathSegmentCharsForPlatform(); + char[] sanitizedChars = [.. name.Trim().Select(character => Array.IndexOf(invalidChars, character) >= 0 ? ' ' : character)]; + + // collapse the consecutive whitespace into a single space, so that the segment does not contain ragged spacing + List collapsedChars = []; + bool previousWasWhitespace = false; + foreach (char character in sanitizedChars) + { + if (char.IsWhiteSpace(character)) + { + if (!previousWasWhitespace) + collapsedChars.Add(' '); + previousWasWhitespace = true; + } + else + { + collapsedChars.Add(character); + previousWasWhitespace = false; + } + } + + string sanitized = new string([.. collapsedChars]).Trim(); + if (string.Equals(sanitized, ".", StringComparison.Ordinal) || string.Equals(sanitized, "..", StringComparison.Ordinal)) + return Errors.FileSystemManagement.InvalidPath; + // a segment must never contain a path separator, otherwise the segment could escape its directory or nest additional directories + if (sanitized.Contains('/') || sanitized.Contains('\\')) + return Errors.FileSystemManagement.InvalidPath; + if (sanitized.Length > MAX_DIRECTORY_SEGMENT_LENGTH) + sanitized = sanitized[..MAX_DIRECTORY_SEGMENT_LENGTH].TrimEnd(); + if (sanitized.Length == 0) + return Errors.FileSystemManagement.InvalidPath; + + return PathSegment.Create(sanitized, isDirectory: true, isDrive: false); + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs index ffd4e584..2d36653b 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/IPathStrategy.cs @@ -11,7 +11,7 @@ namespace Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext. /// public interface IPathStrategy { - public char PathSeparator { get; } + char PathSeparator { get; } /// /// Checks if is a valid path. @@ -56,6 +56,12 @@ public interface IPathStrategy /// A collection of characters that are invalid in the context of paths char[] GetInvalidPathCharsForPlatform(); + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + char[] GetInvalidPathSegmentCharsForPlatform(); + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs index 1aa7dacc..2b6039e5 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategy.cs @@ -154,6 +154,15 @@ public class UnixPathStrategy : IUnixPathStrategy return ['\0']; } + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + public char[] GetInvalidPathSegmentCharsForPlatform() + { + return ['\0']; + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs index 6639883c..396dee6f 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategy.cs @@ -113,7 +113,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy // handle UNC path yield return PathSegment.Create(@"\\", isDirectory: false, isDrive: true); - string[] segments = path.Path[2..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + string[] segments = path.Path[2..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) yield return CreatePathSegment(segments[i], i, segments.Length); } @@ -122,7 +122,7 @@ public class WindowsPathStrategy : IWindowsPathStrategy // the drive segment yield return PathSegment.Create(path.Path[..2], isDirectory: false, isDrive: true); // extract the other segments - string[] segments = path.Path[3..].Split(new[] { PathSeparator }, StringSplitOptions.RemoveEmptyEntries); + string[] segments = path.Path[3..].Split([PathSeparator], StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < segments.Length; i++) { string segment = segments[i]; @@ -190,6 +190,15 @@ public class WindowsPathStrategy : IWindowsPathStrategy return ['<', '>', '"', '/', '|', '?', '*']; } + /// + /// Returns a collection of characters that are invalid for a single path segment. + /// + /// A collection of characters that are invalid in the context of a single path segment. + public char[] GetInvalidPathSegmentCharsForPlatform() + { + return ['<', '>', '"', '/', '|', '?', '*', ':']; + } + /// /// Returns the root portion of the given path. /// diff --git a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs index 0a471cde..11c3a0e1 100644 --- a/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs +++ b/src/Lumina.Infrastructure/Core/Themes/ThemeService.cs @@ -3,6 +3,8 @@ using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -12,7 +14,6 @@ using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; -using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading; @@ -41,10 +42,6 @@ public sealed class ThemeService : IThemeService "^[0-9]+\\.[0-9]+\\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - private static readonly Regex s_pathSegmentPattern = new( - "^[A-Za-z0-9][A-Za-z0-9._ -]*$", - RegexOptions.Compiled | RegexOptions.CultureInvariant); - private static readonly JsonSerializerOptions s_manifestJsonOptions = new(JsonSerializerDefaults.Web) { PropertyNameCaseInsensitive = true, @@ -64,16 +61,19 @@ public sealed class ThemeService : IThemeService // resolved storage root. private static readonly ConcurrentDictionary s_storageGates = new(StringComparer.Ordinal); private readonly SemaphoreSlim _mutationGate; + private readonly IPathService _pathService; /// /// Initializes a new instance of the class. /// /// The theme engine configuration options. /// The logger for this service. - public ThemeService(IOptions options, ILogger logger) + /// The service used to validate the path segments of the theme packages. + public ThemeService(IOptions options, ILogger logger, IPathService pathService) { _options = options.Value; _logger = logger; + _pathService = pathService; string basePath = AppContext.BaseDirectory; _storageRoot = ResolvePath(basePath, _options.StoragePath); _stagingRoot = Path.Combine(_storageRoot, ".staging"); @@ -279,7 +279,7 @@ public sealed class ThemeService : IThemeService /// The absolute path of the theme pack directory. /// The page key that selects the template. /// The mirrored template path, or when no mirrored template exists. - private static string? ResolveMirroredTemplatePath(string themePath, string pageKey) + private string? ResolveMirroredTemplatePath(string themePath, string pageKey) { string? candidate = pageKey; while (candidate is not null) @@ -516,7 +516,7 @@ public sealed class ThemeService : IThemeService /// /// The absolute path of the theme pack directory. /// An containing either the parsed manifest, or an error. - private static Result LoadManifestFromDirectory(string themeRoot) + private Result LoadManifestFromDirectory(string themeRoot) { string manifestPath = Path.Combine(themeRoot, MANIFEST_FILE_NAME); if (!File.Exists(manifestPath)) @@ -580,7 +580,7 @@ public sealed class ThemeService : IThemeService /// The absolute path of the theme pack directory. /// The manifest to validate. /// An representing either a successful operation, or an error. - private static Result ValidateManifest(string themeRoot, ThemeManifestDto manifest) + private Result ValidateManifest(string themeRoot, ThemeManifestDto manifest) { if (manifest.SchemaVersion != 1) return PackageInvalid("Only theme schemaVersion 1 is supported."); @@ -700,7 +700,7 @@ public sealed class ThemeService : IThemeService /// The package-relative path to normalize. /// Whether a trailing slash, used for directory entries, is permitted. /// An containing either the normalized path, or an error. - private static Result NormalizeRelativePath(string path, bool allowTrailingSlash = false) + private Result NormalizeRelativePath(string path, bool allowTrailingSlash = false) { if (string.IsNullOrWhiteSpace(path) || path.Length > 240 || path.Contains('\\') || path.Contains('\0') || path.StartsWith('/') || path.Contains("//")) return PackageInvalid("The theme contains an invalid path."); @@ -714,9 +714,16 @@ public sealed class ThemeService : IThemeService return PackageInvalid("A theme path is nested too deeply."); foreach (string segment in segments) - if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.') || !s_pathSegmentPattern.IsMatch(segment)) + { + if (segment is "." or ".." || segment.Length > 80 || segment.EndsWith(' ') || segment.EndsWith('.')) return PackageInvalid($"Theme path segment '{segment}' is invalid."); + // a theme path segment must be already safe, meaning that sanitizing it would leave it unchanged + Result sanitizeResult = _pathService.SanitizeSegment(segment); + if (sanitizeResult.IsFailure || !string.Equals(sanitizeResult.Value.Name, segment, StringComparison.Ordinal)) + return PackageInvalid($"Theme path segment '{segment}' is invalid."); + } + return string.Join('/', segments); } @@ -811,7 +818,7 @@ public sealed class ThemeService : IThemeService /// A task representing the asynchronous operation. private static async Task SwapIntoDestinationAsync(string extractionPath, string destination, CancellationToken cancellationToken) { - const int maxAttempts = 10; + const int MAX_ATTEMPTS = 10; for (int attempt = 1; ; attempt++) { try @@ -822,7 +829,7 @@ public sealed class ThemeService : IThemeService Directory.Move(extractionPath, destination); return; } - catch (IOException) when (attempt < maxAttempts) + catch (IOException) when (attempt < MAX_ATTEMPTS) { await Task.Delay(100 * attempt, cancellationToken); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs index ba9710aa..cf0803aa 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/PathServiceTests.cs @@ -520,4 +520,241 @@ public class PathServiceTests Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); _mockPathStrategy.DidNotReceive().GetPathRoot(Arg.Any()); } + + [Fact] + public void SanitizeSegment_WithValidName_ShouldReturnTheNameAsASegment() + { + // Arrange + char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*']; + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars); + + // Act + Result result = _sut.SanitizeSegment("Valid Name"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Valid Name", result.Value.Name); + _mockPathStrategy.Received(1).GetInvalidPathSegmentCharsForPlatform(); + } + + [Fact] + public void SanitizeSegment_WithLeadingAndTrailingWhitespace_ShouldTrimTheName() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(" Valid Name "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Valid Name", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithInvalidCharacters_ShouldReplaceThemWithSpaces() + { + // Arrange + char[] invalidChars = ['<', '>', ':', '"', '|', '?', '*']; + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(invalidChars); + + // Act + Result result = _sut.SanitizeSegment("Bad"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Bad Name", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithConsecutiveWhitespace_ShouldCollapseItIntoASingleSpace() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment("Name with spaces"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Name with spaces", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithDotSegment_ShouldReturnInvalidPath() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment("."); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithDotDotSegment_ShouldReturnInvalidPath() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(".."); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithForwardSlash_ShouldReturnInvalidPath() + { + // Arrange + // the forward slash is not an invalid character for a segment on Unix-like platforms, so only the path service can reject it + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']); + + // Act + Result result = _sut.SanitizeSegment("a/b"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithBackslash_ShouldReturnInvalidPath() + { + // Arrange + // the backslash is not an invalid character for a segment on Windows platforms, so only the path service can reject it + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']); + + // Act + Result result = _sut.SanitizeSegment("a\\b"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Theory] + [InlineData("../..")] // parent directory escape + [InlineData("a/../b")] // embedded parent directory escape + [InlineData("..\\..")] // Windows parent directory escape + [InlineData("a\\..\\b")] // embedded Windows parent directory escape + public void SanitizeSegment_WithPathTraversal_ShouldReturnInvalidPath(string name) + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']); + + // Act + Result result = _sut.SanitizeSegment(name); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithAColon_WhenTheColonIsValidForThePlatform_ShouldKeepTheColon() + { + // Arrange + // the colon is not an invalid character for a segment on Unix-like platforms, so it must be preserved + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['\0']); + + // Act + Result result = _sut.SanitizeSegment("Name:WithColon"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Name:WithColon", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithAColon_WhenTheColonIsInvalidForThePlatform_ShouldReplaceItWithASpace() + { + // Arrange + // the colon is an invalid character for a segment on Windows platforms, so it must be replaced + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', '"', '|', '?', '*', ':']); + + // Act + Result result = _sut.SanitizeSegment("Name:WithColon"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Name WithColon", result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithEmptyName_ShouldReturnNameCannotBeEmpty() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(string.Empty); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + _mockPathStrategy.DidNotReceive().GetInvalidPathSegmentCharsForPlatform(); + } + + [Fact] + public void SanitizeSegment_WithWhitespaceOnlyName_ShouldReturnNameCannotBeEmpty() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(" "); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.NameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithNameMadeOnlyOfInvalidCharacters_ShouldReturnInvalidPath() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment("***"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void SanitizeSegment_WithNameLongerThanTheMaximumLength_ShouldCapTheSegment() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(new string('a', 150)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(100, result.Value.Name.Length); + Assert.Equal(new string('a', 100), result.Value.Name); + } + + [Fact] + public void SanitizeSegment_WithNameLongerThanTheMaximumLengthAndTrailingWhitespace_ShouldTrimAfterCapping() + { + // Arrange + _mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(['<', '>', ':', '"', '|', '?', '*']); + + // Act + Result result = _sut.SanitizeSegment(new string('a', 110) + new string(' ', 50)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(100, result.Value.Name.Length); + } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs index 715a5434..c79f6fc3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/UnixPathStrategyTests.cs @@ -507,6 +507,40 @@ public class UnixPathStrategyTests Assert.Equal(result1, result2); } + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnOnlyNullCharacter() + { + // Act + char[] result = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.Single(result); + Assert.Contains('\0', result); + } + + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldNotContainTheColon() + { + // Act + char[] result = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.DoesNotContain(':', result); + Assert.DoesNotContain('/', result); + Assert.DoesNotContain('\\', result); + } + + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls() + { + // Act + char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform(); + char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.Equal(result1, result2); + } + [Fact] public void GetPathRoot_WithValidUnixPath_ShouldReturnRootSegment() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs index 48d903a4..a01a5f9b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Strategies/Path/WindowsPathStrategyTests.cs @@ -625,6 +625,39 @@ public class WindowsPathStrategyTests Assert.Equal(result1, result2); } + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnExpectedCharacters() + { + // Act + char[] result = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.Equal(['<', '>', '"', '/', '|', '?', '*', ':'], result); + } + + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldContainTheColon() + { + // Act + char[] result = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.Contains(':', result); + Assert.DoesNotContain('\\', result); + Assert.DoesNotContain('\0', result); + } + + [Fact] + public void GetInvalidPathSegmentCharsForPlatform_WhenCalled_ShouldReturnSameResultOnMultipleCalls() + { + // Act + char[] result1 = _sut.GetInvalidPathSegmentCharsForPlatform(); + char[] result2 = _sut.GetInvalidPathSegmentCharsForPlatform(); + + // Assert + Assert.Equal(result1, result2); + } + [Fact] public void GetPathRoot_WithValidWindowsPath_ShouldReturnRootSegment() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs index 204d80d3..f8ec2512 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Infrastructure.Common.Models.DTO.Configuration; using Lumina.Infrastructure.Core.Themes; using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; @@ -55,26 +57,6 @@ public class ThemeServiceTests : IDisposable _sut = CreateSut(_options); } - /// - /// Cleans up the temporary storage used by the tests. - /// - public void Dispose() - { - try - { - if (Directory.Exists(_testRootPath)) - Directory.Delete(_testRootPath, recursive: true); - } - catch (IOException) - { - // best effort cleanup of the per-test temp directory - } - catch (UnauthorizedAccessException) - { - // best effort cleanup of the per-test temp directory - } - } - [Fact] public void MaxArchiveBytes_WhenConfigured_ShouldReturnConfiguredValue() { @@ -1151,6 +1133,26 @@ public class ThemeServiceTests : IDisposable Assert.False(_sut.HasThemePack("bundled-theme")); } + /// + /// Cleans up the temporary storage used by the tests. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_testRootPath)) + Directory.Delete(_testRootPath, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the per-test temp directory + } + catch (UnauthorizedAccessException) + { + // best effort cleanup of the per-test temp directory + } + } + /// /// Creates a valid theme pack that declares the default, home and library templates and their files. /// @@ -1207,6 +1209,9 @@ public class ThemeServiceTests : IDisposable private static ThemeService CreateSut(ThemeEngineOptionsDto options) { ILogger logger = Substitute.For>(); - return new ThemeService(Options.Create(options), logger); + IPathService pathService = Substitute.For(); + pathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => PathSegment.Create(callInfo.Arg(), isDirectory: true, isDrive: false)); + return new ThemeService(Options.Create(options), logger, pathService); } } From 7aeed04255fabaafba44ec47d5b26364f8eae598 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:19:45 -0700 Subject: [PATCH 5/7] Adds test fixtures and endpoint test coverage --- .../DTO/Filtering/BaseFilterDtoFixture.cs | 41 +++++ .../DTO/Filtering/LibraryFilterDtoFixture.cs | 52 ++++++ .../Pagination/PaginatedResultDtoFixture.cs | 55 +++++++ .../Pagination/PaginationDataDtoFixture.cs | 45 +++++ .../Authorization/RoleEntityFixture.cs | 61 +++++++ .../Entities/Common/GenreEntityFixture.cs | 41 +++++ .../Entities/Common/TagEntityFixture.cs | 41 +++++ .../BookLibrary/IsbnEntityFixture.cs | 46 ++++++ .../DTO/Themes/ThemeArchiveDtoFixture.cs | 46 ++++++ .../Models/DTO/Themes/ThemeAssetDtoFixture.cs | 43 +++++ .../GetPermissionsQueryFixture.cs | 34 ++++ .../CheckInitializationQueryFixture.cs | 34 ++++ .../CancelLibrariesScanCommandFixture.cs | 34 ++++ .../ScanLibrariesCommandFixture.cs | 34 ++++ .../GetEnabledLibrariesQueryFixture.cs | 34 ++++ .../GetLibraries/GetLibrariesQueryFixture.cs | 34 ++++ .../GetRunningLibraryScansQueryFixture.cs | 34 ++++ .../GetPlugins/GetPluginsQueryFixture.cs | 34 ++++ .../GetUserSettingsQueryFixture.cs | 34 ++++ .../Core/DTO/Common/GenreDtoFixture.cs | 41 +++++ .../Core/DTO/Common/LanguageInfoDtoFixture.cs | 46 ++++++ .../Core/DTO/Common/ReleaseInfoDtoFixture.cs | 53 ++++++ .../Core/DTO/Common/TagDtoFixture.cs | 41 +++++ .../MediaContributorDtoFixture.cs | 45 +++++ .../MediaContributorNameDtoFixture.cs | 43 +++++ .../MediaContributorRoleDtoFixture.cs | 43 +++++ .../WrittenContentMetadataDtoFixture.cs | 65 ++++++++ .../Authorization/AddRoleRequestFixture.cs | 42 +++++ .../Authorization/DeleteRoleRequestFixture.cs | 40 +++++ .../GetRolePermissionsRequestFixture.cs | 37 +++++ .../GetUserPermissionsRequestFixture.cs | 37 +++++ .../GetUserRoleRequestFixture.cs | 37 +++++ .../Books/GetBookRequestFixture.cs | 37 +++++ .../ChangePasswordResponseFixture.cs | 39 +++++ .../Authentication/LoginResponseFixture.cs | 50 ++++++ .../RecoverPasswordResponseFixture.cs | 39 +++++ .../AuthorizationResponseFixture.cs | 48 ++++++ .../Authorization/RoleResponseFixture.cs | 42 +++++ .../FileSystemTypeResponseFixture.cs | 40 +++++ .../Path/PathExistsResponseFixture.cs | 39 +++++ .../Path/PathValidResponseFixture.cs | 39 +++++ .../MediaLibraryScanResponseFixture.cs | 39 +++++ .../InitializationResponseFixture.cs | 39 +++++ .../Common/PaginatedResponseFixture.cs | 55 +++++++ .../DTO/Authorization/PermissionDtoFixture.cs | 46 ++++++ .../RolePermissionsDtoFixture.cs | 43 +++++ .../DTO/Common/ProblemDetailsDtoFixture.cs | 54 ++++++ .../EncryptionSettingsDtoFixture.cs | 42 +++++ .../ServerConfigurationDtoFixture.cs | 48 ++++++ .../BlobDataDtoFixture.cs | 45 +++++ .../DirectoryDtoFixture.cs | 54 ++++++ .../FileSystemManagement/FileDtoFixture.cs | 52 ++++++ .../FileSystemTreeNodeDtoFixture.cs | 54 ++++++ .../FileSystemTypeDtoFixture.cs | 43 +++++ .../PathExistsDtoFixture.cs | 41 +++++ .../PathSegmentDtoFixture.cs | 42 +++++ .../PathSeparatorDtoFixture.cs | 41 +++++ .../PathValidDtoFixture.cs | 41 +++++ .../DTO/Libraries/BookLiteDtoFixture.cs | 56 +++++++ .../LibraryScanJobProgressDtoFixture.cs | 53 ++++++ .../LibraryScanProgressDtoFixture.cs | 66 ++++++++ .../Libraries/PaginatedBookLiteDtoFixture.cs | 54 ++++++ .../DTO/Themes/ThemeLayoutPageDtoFixture.cs | 46 ++++++ .../DTO/Themes/ThemeNavEntryDtoFixture.cs | 53 ++++++ .../DTO/Themes/ThemeNavSectionDtoFixture.cs | 44 +++++ .../Themes/ThemePageRenderResultDtoFixture.cs | 44 +++++ .../DTO/UsersManagement/UserDtoFixture.cs | 45 +++++ .../Authorization/UpdateRoleRequestFixture.cs | 48 ++++++ ...ateUserRoleAndPermissionsRequestFixture.cs | 45 +++++ .../Books/GetBooksViewRequestFixture.cs | 39 +++++ .../Themes/DeleteThemeRequestFixture.cs | 38 +++++ .../Themes/GetThemeArchiveRequestFixture.cs | 38 +++++ .../Themes/GetThemeAssetRequestFixture.cs | 41 +++++ .../Themes/RestoreThemeRequestFixture.cs | 38 +++++ .../Themes/SetCurrentThemeRequestFixture.cs | 38 +++++ .../GetAuthorizationResponseFixture.cs | 49 ++++++ .../ChangePasswordResponseFixture.cs | 39 +++++ .../RecoverPasswordResponseFixture.cs | 39 +++++ .../RegisterResponseFixture.cs | 44 +++++ .../Roles/AddRole/AddRoleEndpointTests.cs | 93 +++++++++++ .../DeleteRole/DeleteRoleEndpointTests.cs | 89 ++++++++++ .../GetRolePermissionsEndpointTests.cs | 78 +++++++++ .../UpdateRole/UpdateRoleEndpointTests.cs | 93 +++++++++++ .../ManagePermissionsViewEndpointTests.cs | 78 +++++++++ .../ManageRolesViewEndpointTests.cs | 73 +++++++++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 82 ++++++++++ .../DownloadThemeEndpointTests.cs | 70 ++++++++ .../GetThemes/GetThemesEndpointTests.cs | 69 ++++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 96 +++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 64 ++++++++ .../SetCurrentThemeEndpointTests.cs | 65 ++++++++ .../Themes/ThemesIndexViewEndpointTests.cs | 54 ++++++ .../GetUserPermissionsEndpointTests.cs | 78 +++++++++ .../GetUserRole/GetUserRoleEndpointTests.cs | 78 +++++++++ ...dateUserRoleAndPermissionsEndpointTests.cs | 94 +++++++++++ .../GetDirectoriesEndpointTests.cs | 61 +++++++ .../GetDrives/GetDrivesEndpointTests.cs | 58 +++++++ .../GetType/GetTypeEndpointTests.cs | 57 +++++++ .../Files/GetFiles/GetFilesEndpointTests.cs | 61 +++++++ .../GetTreeFiles/GetTreeFilesEndpointTests.cs | 61 +++++++ .../CheckPathExistsEndpointTests.cs | 59 +++++++ .../GetPathParentEndpointTests.cs | 61 +++++++ .../GetPathRoot/GetPathRootEndpointTests.cs | 59 +++++++ .../GetPathSeparatorEndpointTests.cs | 57 +++++++ .../Path/SplitPath/SplitPathEndpointTests.cs | 66 ++++++++ .../ValidatePath/ValidatePathEndpointTests.cs | 59 +++++++ .../Endpoints/Home/HomeErrorEndpointTests.cs | 46 ++++++ .../Home/HomeNotFoundViewEndpointTests.cs | 44 +++++ .../Home/HomePrivacyEndpointTests.cs | 46 ++++++ .../AddLibrary/AddLibraryViewEndpointTests.cs | 45 +++++ .../CancelLibrariesScanEndpointTests.cs | 71 ++++++++ .../CancelLibraryScanEndpointTests.cs | 74 +++++++++ .../DeleteLibraryEndpointTests.cs | 74 +++++++++ .../EditLibraryViewEndpointTests.cs | 53 ++++++ .../GetEnabledLibrariesEndpointTests.cs | 82 ++++++++++ .../GetMetadataProvidersEndpointTests.cs | 84 ++++++++++ .../GetRunningLibraryScansEndpointTests.cs | 82 ++++++++++ .../Index/LibrariesIndexViewEndpointTests.cs | 45 +++++ .../ReorderMetadataProvidersEndpointTests.cs | 71 ++++++++ .../ScanLibrariesEndpointTests.cs | 81 +++++++++ .../ScanLibrary/ScanLibraryEndpointTests.cs | 78 +++++++++ ...SetMetadataProviderEnabledEndpointTests.cs | 71 ++++++++ .../EditBook/EditBookViewEndpointTests.cs | 48 ++++++ .../GetLibraryItemsEndpointTests.cs | 63 +++++++ .../Index/BooksIndexViewEndpointTests.cs | 70 ++++++++ .../GetPluginSettingsEndpointTests.cs | 61 +++++++ .../Index/PluginsIndexViewEndpointTests.cs | 55 +++++++ .../ThemeAssets/ThemeAssetsEndpointTests.cs | 68 ++++++++ .../AccessDeniedViewEndpointTests.cs | 44 +++++ .../ChangePasswordEndpointTests.cs | 81 +++++++++ .../ChangePasswordViewEndpointTests.cs | 46 ++++++ .../Logout/LogoutEndpointTests.cs | 44 +++++ .../RecoverPasswordEndpointTests.cs | 80 +++++++++ .../RecoverPasswordViewEndpointTests.cs | 46 ++++++ .../Register/RegisterEndpointTests.cs | 103 ++++++++++++ .../Register/RegisterViewEndpointTests.cs | 46 ++++++ .../CheckInitializationEndpointTests.cs | 41 +++++ .../SetupApplicationEndpointTests.cs | 92 +++++++++++ .../Roles/AddRole/AddRoleEndpointTests.cs | 139 ++++++++++++++++ .../DeleteRole/DeleteRoleEndpointTests.cs | 136 ++++++++++++++++ .../GetRolePermissionsEndpointTests.cs | 80 +++++++++ .../UpdateRole/UpdateRoleEndpointTests.cs | 139 ++++++++++++++++ .../ManagePermissionsViewEndpointTests.cs | 91 +++++++++++ .../ManageRolesViewEndpointTests.cs | 86 ++++++++++ .../DeleteTheme/DeleteThemeEndpointTests.cs | 80 +++++++++ .../DownloadThemeEndpointTests.cs | 45 +++++ .../GetThemes/GetThemesEndpointTests.cs | 46 ++++++ .../InstallTheme/InstallThemeEndpointTests.cs | 84 ++++++++++ .../RestoreTheme/RestoreThemeEndpointTests.cs | 80 +++++++++ .../SetCurrentThemeEndpointTests.cs | 80 +++++++++ .../Themes/ThemesIndexViewEndpointTests.cs | 43 +++++ .../GetUserPermissionsEndpointTests.cs | 81 +++++++++ .../GetUserRole/GetUserRoleEndpointTests.cs | 80 +++++++++ ...dateUserRoleAndPermissionsEndpointTests.cs | 137 ++++++++++++++++ .../GetDirectoriesEndpointTests.cs | 74 +++++++++ .../GetDrives/GetDrivesEndpointTests.cs | 43 +++++ .../GetType/GetTypeEndpointTests.cs | 43 +++++ .../Files/GetFiles/GetFilesEndpointTests.cs | 74 +++++++++ .../GetTreeFiles/GetTreeFilesEndpointTests.cs | 43 +++++ .../CheckPathExistsEndpointTests.cs | 75 +++++++++ .../GetPathParentEndpointTests.cs | 74 +++++++++ .../GetPathRoot/GetPathRootEndpointTests.cs | 75 +++++++++ .../GetPathSeparatorEndpointTests.cs | 43 +++++ .../Path/SplitPath/SplitPathEndpointTests.cs | 74 +++++++++ .../ValidatePath/ValidatePathEndpointTests.cs | 75 +++++++++ .../Endpoints/Home/HomeErrorEndpointTests.cs | 41 +++++ .../Endpoints/Home/HomeIndexEndpointTests.cs | 61 +++++++ .../Home/HomeNotFoundViewEndpointTests.cs | 41 +++++ .../Home/HomePrivacyEndpointTests.cs | 41 +++++ .../AddLibrary/AddLibraryViewEndpointTests.cs | 42 +++++ .../CancelLibrariesScanEndpointTests.cs | 80 +++++++++ .../CancelLibraryScanEndpointTests.cs | 85 ++++++++++ .../EditLibraryViewEndpointTests.cs | 44 +++++ .../GetEnabledLibrariesEndpointTests.cs | 46 ++++++ .../GetLibraries/GetLibrariesEndpointTests.cs | 46 ++++++ .../GetMetadataProvidersEndpointTests.cs | 47 ++++++ .../GetRunningLibraryScansEndpointTests.cs | 46 ++++++ .../Index/LibrariesIndexViewEndpointTests.cs | 42 +++++ .../ReorderMetadataProvidersEndpointTests.cs | 89 ++++++++++ .../ScanLibrariesEndpointTests.cs | 80 +++++++++ .../ScanLibrary/ScanLibraryEndpointTests.cs | 114 +++++++++++++ ...SetMetadataProviderEnabledEndpointTests.cs | 93 +++++++++++ .../EditBook/EditBookViewEndpointTests.cs | 42 +++++ .../GetLibraryItemsEndpointTests.cs | 76 +++++++++ .../Index/BooksIndexViewEndpointTests.cs | 43 +++++ .../GetPluginSettingsEndpointTests.cs | 78 +++++++++ .../Index/PluginsIndexViewEndpointTests.cs | 43 +++++ .../ThemeAssets/ThemeAssetsEndpointTests.cs | 97 +++++++++++ .../SetLanguage/SetLanguageEndpointTests.cs | 41 +++++ .../AccessDeniedViewEndpointTests.cs | 42 +++++ .../ChangePasswordEndpointTests.cs | 154 ++++++++++++++++++ .../ChangePasswordViewEndpointTests.cs | 41 +++++ .../Login/LoginViewEndpointTests.cs | 44 +++++ .../Logout/LogoutEndpointTests.cs | 42 +++++ .../RecoverPasswordEndpointTests.cs | 130 +++++++++++++++ .../RecoverPasswordViewEndpointTests.cs | 42 +++++ .../Register/RegisterEndpointTests.cs | 130 +++++++++++++++ .../Register/RegisterViewEndpointTests.cs | 42 +++++ 198 files changed, 11649 insertions(+) create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs new file mode 100644 index 00000000..24071540 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/BaseFilterDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Filtering; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BaseFilterDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The search term used to filter results. + /// The created . + public BaseFilterDto Create(string? searchTerm = null) + { + return new BaseFilterDto + { + SearchTerm = searchTerm ?? _faker.Lorem.Sentence() + }; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs new file mode 100644 index 00000000..f9a8971d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Filtering/LibraryFilterDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Filtering; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Filtering; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryFilterDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library used to filter data. + /// Optional. The search term used to filter results. + /// Optional. The alpha key used to filter by the first character of the item title. + /// Whether the leading "The " prefix should be ignored when computing the alpha key, or not. + /// The created . + public LibraryFilterDto Create( + Guid? libraryId = null, + string? searchTerm = null, + string? filterAlphaKey = null, + bool shouldIgnoreThePrefixForAlphaPicker = false) + { + return new LibraryFilterDto + { + LibraryId = libraryId ?? _faker.Random.Guid(), + SearchTerm = searchTerm, + FilterAlphaKey = filterAlphaKey, + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs new file mode 100644 index 00000000..0cdc69be --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginatedResultDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Pagination; + +/// +/// Fixture class for the record. +/// +/// The type of the data items contained in the paginated result. +[ExcludeFromCodeCoverage] +public class PaginatedResultDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The collection of data items. + /// Optional. The current page number. + /// Optional. The number of items per page. + /// Optional. The total number of elements available. + /// Optional. The total number of pages. + /// The created . + public PaginatedResultDto Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedResultDto + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List> CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs new file mode 100644 index 00000000..2bbc63cf --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Pagination/PaginationDataDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Pagination; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Pagination; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PaginationDataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The current page number in a paginated collection. + /// Optional. The number of items to include per page in paginated results. + /// The created . + public PaginationDataDto Create( + int? currentPage = null, + int? perPage = null) + { + return new PaginationDataDto + { + CurrentPage = currentPage ?? _faker.Random.Int(1, 100), + PerPage = perPage ?? _faker.Random.Int(1, 200) + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs new file mode 100644 index 00000000..3ffee2c1 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RoleEntityFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class RoleEntityFixture +{ + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role. + /// Optional. The name of the role. + /// Optional. The role permission associations of the role. + /// Whether the role should include role permission associations or not. + /// Optional. The Id of the user that created the role. + /// Optional. The time and date when the role was added. + /// The created . + public RoleEntity Create( + Guid? id = null, + string? roleName = null, + IEnumerable? rolePermissions = null, + bool includeRolePermissions = false, + Guid? createdBy = null, + DateTime? createdOnUtc = null) + { + return new Faker() + .CustomInstantiator(faker => new RoleEntity + { + Id = id ?? faker.Random.Guid(), + RoleName = roleName ?? faker.Random.String2(faker.Random.Number(1, 50)), + RolePermissions = includeRolePermissions ? (rolePermissions ?? _rolePermissionEntityFixture.CreateMany()).ToList() : [], + CreatedOnUtc = createdOnUtc ?? faker.Date.Past(), + CreatedBy = createdBy ?? faker.Random.Guid(), + UpdatedOnUtc = null, + UpdatedBy = null + }) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs new file mode 100644 index 00000000..a0cc7ad3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/GenreEntityFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GenreEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the genre. + /// Whether the name should be included, or forced to . + /// The created . + public GenreEntity Create( + string? name = null, + bool includeName = true) + { + return new GenreEntity(includeName ? name ?? _faker.Lorem.Word() : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs new file mode 100644 index 00000000..1985f046 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Common/TagEntityFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TagEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// The created . + public TagEntity Create( + string? name = null, + bool includeName = true) + { + return new TagEntity(includeName ? name ?? _faker.Lorem.Word() : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs new file mode 100644 index 00000000..0ad25a7d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnEntityFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class IsbnEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISBN value. + /// Optional. The format of the ISBN. + /// Whether the value should be included, or forced to . + /// The created . + public IsbnEntity Create( + string? value = null, + IsbnFormat? format = null, + bool includeValue = true) + { + return new IsbnEntity( + includeValue ? value ?? _faker.Random.String2(13, "0123456789") : null, + format); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs new file mode 100644 index 00000000..103743bb --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeArchiveDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeArchiveDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the ZIP archive. + /// Optional. The file name to expose when downloading the archive. + /// Optional. The MIME content type of the archive. + /// The created . + public ThemeArchiveDto Create( + byte[]? bytes = null, + string? fileName = null, + string? contentType = null) + { + return new ThemeArchiveDto( + bytes ?? _faker.Random.Bytes(10), + fileName ?? _faker.System.FileName(), + contentType ?? _faker.System.MimeType()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs new file mode 100644 index 00000000..dce663b9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Themes/ThemeAssetDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The bytes of the asset file. + /// Optional. The MIME content type of the asset file. + /// The created . + public ThemeAssetDto Create( + byte[]? bytes = null, + string? contentType = null) + { + return new ThemeAssetDto( + bytes ?? _faker.Random.Bytes(10), + contentType ?? _faker.System.MimeType()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs new file mode 100644 index 00000000..962a415c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Admin.Authorization.Permissions.Queries.GetPermissions; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPermissionsQueryFixture +{ + /// + /// Creates a random valid query to get permissions. + /// + /// The created query. + public GetPermissionsQuery Create() + { + return new GetPermissionsQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs new file mode 100644 index 00000000..5bf4cfed --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public CheckInitializationQuery Create() + { + return new CheckInitializationQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs new file mode 100644 index 00000000..0c35040a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanCommandFixture +{ + /// + /// Creates a . + /// + /// The created . + public CancelLibrariesScanCommand Create() + { + return new CancelLibrariesScanCommand(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs new file mode 100644 index 00000000..69e2519a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.ScanLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesCommandFixture +{ + /// + /// Creates a . + /// + /// The created . + public ScanLibrariesCommand Create() + { + return new ScanLibrariesCommand(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs new file mode 100644 index 00000000..df7be1bc --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetEnabledLibrariesQuery Create() + { + return new GetEnabledLibrariesQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs new file mode 100644 index 00000000..084f8b5d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetLibrariesQuery Create() + { + return new GetLibrariesQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs new file mode 100644 index 00000000..9b322530 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetRunningLibraryScansQuery Create() + { + return new GetRunningLibraryScansQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs new file mode 100644 index 00000000..3b82f852 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPlugins/GetPluginsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetPlugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + public GetPluginsQuery Create() + { + return new GetPluginsQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs new file mode 100644 index 00000000..6fc4a7a9 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsQueryFixture +{ + /// + /// Creates a random valid query to get the settings of the current user. + /// + /// The created query. + public GetUserSettingsQuery Create() + { + return new GetUserSettingsQuery(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs new file mode 100644 index 00000000..24179b03 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/GenreDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GenreDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the genre. + /// Whether the name should be included, or forced to . + /// The created . + public GenreDto Create( + string? name = null, + bool includeName = true) + { + return new GenreDto(includeName ? name ?? _faker.Lorem.Word() : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs new file mode 100644 index 00000000..e67f358d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/LanguageInfoDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISO code of the language. + /// Optional. The name of the language in English. + /// Optional. The native name of the language. + /// The created . + public LanguageInfoDto Create( + string? languageCode = null, + string? languageName = null, + string? nativeName = null) + { + return new LanguageInfoDto( + languageCode ?? _faker.Random.String2(2), + languageName ?? _faker.Lorem.Word(), + nativeName ?? _faker.Lorem.Word()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs new file mode 100644 index 00000000..6de91897 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ReleaseInfoDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoDtoFixture +{ + /// + /// Creates an , preserving the values that are not provided as . + /// + /// Optional. The original release date of the content. + /// Optional. The original release year of the content. + /// Optional. The re-release date of the content. + /// Optional. The re-release year of the content. + /// Optional. The country where the content was released. + /// Optional. The version or edition of the content's release. + /// The created . + public ReleaseInfoDto Create( + DateOnly? originalReleaseDate = null, + int? originalReleaseYear = null, + DateOnly? reReleaseDate = null, + int? reReleaseYear = null, + string? releaseCountry = null, + string? releaseVersion = null) + { + return new ReleaseInfoDto( + originalReleaseDate, + originalReleaseYear, + reReleaseDate, + reReleaseYear, + releaseCountry, + releaseVersion); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs new file mode 100644 index 00000000..4dd94b80 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/TagDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TagDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// The created . + public TagDto Create( + string? name = null, + bool includeName = true) + { + return new TagDto(includeName ? name ?? _faker.Lorem.Word() : null); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs new file mode 100644 index 00000000..6082894e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The display name of the media contributor. + /// Optional. The name of the role assigned to the media contributor. + /// Optional. The category of the role. + /// The created . + public MediaContributorDto Create( + string? displayName = null, + string? roleName = null, + string? roleCategory = null) + { + return new MediaContributorDto( + Name: new MediaContributorNameDto(DisplayName: displayName ?? _faker.Name.FullName(), LegalName: null), + Role: new MediaContributorRoleDto(Name: roleName ?? _faker.Commerce.Department(), Category: roleCategory ?? "Writing")); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs new file mode 100644 index 00000000..a332a8a7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorNameDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The display name of the media contributor. + /// Optional. The legal name of the media contributor. + /// The created . + public MediaContributorNameDto Create( + string? displayName = null, + string? legalName = null) + { + return new MediaContributorNameDto( + displayName ?? _faker.Name.FullName(), + legalName ?? _faker.Name.FullName()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs new file mode 100644 index 00000000..93e8d187 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaContributors/MediaContributorRoleDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaContributors; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRoleDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the role assigned to the media contributor. + /// Optional. The category of the role. + /// The created . + public MediaContributorRoleDto Create( + string? name = null, + string? category = null) + { + return new MediaContributorRoleDto( + name ?? _faker.Commerce.Department(), + category ?? _faker.Commerce.Department()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs new file mode 100644 index 00000000..6775e3d6 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoFixture.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataDtoFixture +{ + /// + /// Creates a with the requested values, leaving unspecified properties as . + /// + /// Optional. The title of the written content. + /// Optional. The original title of the written content. + /// Optional. A brief description or summary of the written content. + /// Optional. The release information of the written content. + /// Optional. The genres associated with the written content. + /// Optional. The tags that describe or categorize the written content. + /// Optional. The language in which the written content is written. + /// Optional. The original language of the written content. + /// Optional. The name of the publisher of the written content. + /// Optional. The number of pages in the written content. + /// The created . + public WrittenContentMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + ReleaseInfoDto? releaseInfo = null, + List? genres = null, + List? tags = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, + string? publisher = null, + int? pageCount = null) + { + return new WrittenContentMetadataDto( + title, + originalTitle, + description, + releaseInfo, + genres, + tags, + language, + originalLanguage, + publisher, + pageCount); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs new file mode 100644 index 00000000..a28b3057 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/AddRoleRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the role. + /// Optional. The Ids of the permissions granted to the role. + /// The created . + public AddRoleRequest Create( + string? roleName = null, + List? permissions = null) + { + return new AddRoleRequest(roleName ?? _faker.Commerce.Department(), permissions ?? []); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs new file mode 100644 index 00000000..820d3494 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/DeleteRoleRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role to delete. + /// The created . + public DeleteRoleRequest Create( + Guid? roleId = null) + { + return new DeleteRoleRequest(roleId ?? Guid.NewGuid()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs new file mode 100644 index 00000000..a2a022cf --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetRolePermissionsRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// The Id of the role whose permissions are retrieved. + /// The created . + public GetRolePermissionsRequest Create( + Guid? roleId = null) + { + return new GetRolePermissionsRequest(roleId ?? Guid.NewGuid()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs new file mode 100644 index 00000000..7d597f77 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserPermissionsRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user whose permissions are retrieved. + /// The created . + public GetUserPermissionsRequest Create( + Guid? userId = null) + { + return new GetUserPermissionsRequest(userId ?? Guid.NewGuid()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs new file mode 100644 index 00000000..aa32e308 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/GetUserRoleRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user whose role is retrieved. + /// The created . + public GetUserRoleRequest Create( + Guid? userId = null) + { + return new GetUserRoleRequest(userId ?? Guid.NewGuid()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs new file mode 100644 index 00000000..92ed937f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBookRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the book to retrieve. + /// The created . + public GetBookRequest Create( + string? id = null) + { + return new GetBookRequest(id ?? Guid.NewGuid().ToString()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs new file mode 100644 index 00000000..0f15870a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/ChangePasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was changed. + /// The created . + public ChangePasswordResponse Create( + bool? isPasswordChanged = null) + { + return new ChangePasswordResponse(isPasswordChanged ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs new file mode 100644 index 00000000..43b60891 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/LoginResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the authenticated user. + /// Optional. The username of the authenticated user. + /// Optional. The authentication token of the user. + /// Optional. Whether the user uses two-factor authentication. + /// The created . + public LoginResponse Create( + Guid? id = null, + string? username = null, + string? token = null, + bool? usesTotp = null) + { + return new LoginResponse( + id ?? Guid.NewGuid(), + username ?? _faker.Internet.UserName(), + token ?? _faker.Random.Hexadecimal(32), + usesTotp ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs new file mode 100644 index 00000000..a0a338de --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RecoverPasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authentication; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was reset. + /// The created . + public RecoverPasswordResponse Create( + bool? isPasswordReset = null) + { + return new RecoverPasswordResponse(isPasswordReset ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs new file mode 100644 index 00000000..737bfaeb --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/AuthorizationResponseFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user. + /// Optional. The role of the user. + /// Optional. The permissions of the user. + /// The created . + public AuthorizationResponse Create( + Guid? userId = null, + string? role = null, + IReadOnlySet? permissions = null) + { + return new AuthorizationResponse( + userId ?? Guid.NewGuid(), + role, + permissions ?? new HashSet()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs new file mode 100644 index 00000000..1fdcad3f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RoleResponseFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RoleResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role. + /// Optional. The name of the role. + /// The created . + public RoleResponse Create( + Guid? id = null, + string? roleName = null) + { + return new RoleResponse(id ?? Guid.NewGuid(), roleName ?? _faker.Commerce.Department()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs new file mode 100644 index 00000000..9a33d454 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.FileSystem; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTypeResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The type of the file system platform. + /// The created . + public FileSystemTypeResponse Create( + PlatformType? platformType = null) + { + return new FileSystemTypeResponse(platformType ?? _faker.PickRandom()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs new file mode 100644 index 00000000..3d0d53bf --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathExistsResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PathExistsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the path exists. + /// The created . + public PathExistsResponse Create( + bool? exists = null) + { + return new PathExistsResponse(exists ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs new file mode 100644 index 00000000..d3f9fb85 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Path/PathValidResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PathValidResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the path is valid. + /// The created . + public PathValidResponse Create( + bool? isValid = null) + { + return new PathValidResponse(isValid ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs new file mode 100644 index 00000000..3b9610ef --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library scan. + /// Optional. The Id of the media library the scan belongs to. + /// The created . + public MediaLibraryScanResponse Create( + Guid? scanId = null, + Guid? libraryId = null) + { + return new MediaLibraryScanResponse(scanId ?? Guid.NewGuid(), libraryId ?? Guid.NewGuid()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs new file mode 100644 index 00000000..1d48b9ce --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/InitializationResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class InitializationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the application is initialized. + /// The created . + public InitializationResponse Create( + bool? isInitialized = null) + { + return new InitializationResponse(isInitialized ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs new file mode 100644 index 00000000..007d5790 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Responses/Common/PaginatedResponseFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Responses.Common; + +/// +/// Fixture class for the record. +/// +/// The type of the data items contained in the paginated response. +[ExcludeFromCodeCoverage] +public class PaginatedResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The collection of data items. + /// Optional. The current page number. + /// Optional. The number of items per page. + /// Optional. The total number of elements available. + /// Optional. The total number of pages. + /// The created . + public PaginatedResponse Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedResponse + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List> CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs new file mode 100644 index 00000000..0c21230c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/PermissionDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PermissionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the permission. + /// Optional name of the permission. + /// A configured instance. + public PermissionDto Create( + Guid? id = null, + AuthorizationPermission? permission = null) + { + return new PermissionDto( + Id: id ?? Guid.NewGuid(), + PermissionName: permission ?? _faker.Random.Enum() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs new file mode 100644 index 00000000..9b78d6ff --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RolePermissionsDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RolePermissionsDtoFixture +{ + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The authorization role. + /// Optional. The permissions of the authorization role. + /// The created . + public RolePermissionsDto Create( + RoleDto? role = null, + PermissionDto[]? permissions = null) + { + return new RolePermissionsDto( + role ?? _roleDtoFixture.Create(), + permissions ?? [.. _permissionDtoFixture.CreateMany()]); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs new file mode 100644 index 00000000..fbb0e8e7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Common/ProblemDetailsDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Common; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ProblemDetailsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The URI reference that identifies the problem type. + /// Optional. A short, human-readable summary of the problem type. + /// Optional. The HTTP status code generated by the server. + /// Optional. A detailed explanation specific to this occurrence of the problem. + /// Optional. A URI reference that identifies the specific occurrence of the problem. + /// The created . + public ProblemDetailsDto Create( + string? type = null, + string? title = null, + int? status = null, + string? detail = null, + string? instance = null) + { + return new ProblemDetailsDto + { + Type = type ?? "https://tools.ietf.org/html/rfc4918#section-11.2", + Title = title ?? _faker.Lorem.Word(), + Status = status ?? _faker.Random.Int(400, 599), + Detail = detail ?? _faker.Lorem.Sentence(), + Instance = instance + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs new file mode 100644 index 00000000..38c39d50 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/EncryptionSettingsDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class EncryptionSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The secret key used to encrypt data. + /// The created . + public EncryptionSettingsDto Create( + string? secretKey = null) + { + return new EncryptionSettingsDto + { + SecretKey = secretKey ?? _faker.Random.String2(44, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs new file mode 100644 index 00000000..f07bfccd --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Configuration/ServerConfigurationDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ServerConfigurationDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The remote API server path version. + /// Optional. The remote API server path. + /// Optional. The remote API server port. + /// The created . + public ServerConfigurationDto Create( + char? apiVersion = null, + string? baseAddress = null, + ushort? port = null) + { + return new ServerConfigurationDto + { + ApiVersion = apiVersion ?? _faker.Random.Char('1', '9'), + BaseAddress = baseAddress ?? "http://localhost", + Port = port ?? _faker.Random.UShort() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs new file mode 100644 index 00000000..2f1a331c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/BlobDataDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BlobDataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The binary data as a byte array. + /// Optional. The content type (MIME type) of the blob data. + /// The created . + public BlobDataDto Create( + byte[]? data = null, + string? contentType = null) + { + return new BlobDataDto + { + Data = data ?? _faker.Random.Bytes(32), + ContentType = contentType ?? _faker.System.MimeType() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs new file mode 100644 index 00000000..ce8f3e32 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/DirectoryDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The full path to the directory. + /// Optional. The name of the directory. + /// Optional. The children items of the directory. + /// Whether the directory should include children items, or an empty collection. + /// The created . + public DirectoryDto Create( + string? path = null, + string? name = null, + List? items = null, + bool includeItems = false) + { + string generatedPath = _faker.System.DirectoryPath(); + return new DirectoryDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + DateCreated = _faker.Date.Past(), + DateModified = _faker.Date.Recent(), + Items = includeItems ? (items ?? []) : [] + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs new file mode 100644 index 00000000..fc636ac0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The full path to the file. + /// Optional. The name of the file. + /// Optional. The size of the file, in bytes. + /// A configured instance. + public FileDto Create( + string? path = null, + string? name = null, + long? size = null) + { + string generatedPath = _faker.System.FilePath(); + return new FileDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + DateCreated = _faker.Date.Past(), + DateModified = _faker.Date.Recent(), + Size = size ?? _faker.Random.Long(0, 10_000_000) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs new file mode 100644 index 00000000..513aaae0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTreeNodeDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The full path of the file or directory. + /// Optional. The name of the file or directory. + /// Optional. The type of the item, indicating whether it is a file, directory, or drive. + /// A configured instance. + public FileSystemTreeNodeDto Create( + string? path = null, + string? name = null, + FileSystemItemType? itemType = null) + { + string generatedPath = _faker.System.FilePath(); + return new FileSystemTreeNodeDto + { + Path = path ?? generatedPath, + Name = name ?? Path.GetFileName(generatedPath), + ItemType = itemType ?? _faker.PickRandom(), + IsExpanded = _faker.Random.Bool(), + ChildrenLoaded = _faker.Random.Bool(), + Children = [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs new file mode 100644 index 00000000..e4c61cb2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/FileSystemTypeDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTypeDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system platform type. + /// A configured instance. + public FileSystemTypeDto Create( + PlatformType? platformType = null) + { + return new FileSystemTypeDto + { + PlatformType = platformType ?? _faker.PickRandom() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs new file mode 100644 index 00000000..8b65f0bb --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathExistsDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathExistsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional value indicating whether a file system path exists or not. + /// A configured instance. + public PathExistsDto Create( + bool? exists = null) + { + return new PathExistsDto( + Exists: exists ?? _faker.Random.Bool() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs new file mode 100644 index 00000000..99d78637 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSegmentDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The returned path. + /// A configured instance. + public PathSegmentDto Create( + string? path = null) + { + return new PathSegmentDto + { + Path = path ?? _faker.System.FilePath() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs new file mode 100644 index 00000000..c96d8615 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathSeparatorDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathSeparatorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional file system path separator. + /// A configured instance. + public PathSeparatorDto Create( + string? separator = null) + { + return new PathSeparatorDto( + Separator: separator ?? (_faker.Random.Bool() ? "\\" : "/") + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs new file mode 100644 index 00000000..3bf00678 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/FileSystemManagement/PathValidDtoFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PathValidDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional value indicating whether a file system path is valid or not. + /// A configured instance. + public PathValidDto Create( + bool? isValid = null) + { + return new PathValidDto( + IsValid: isValid ?? _faker.Random.Bool() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs new file mode 100644 index 00000000..c9332206 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/BookLiteDtoFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLiteDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the book. + /// Optional. The title of the book. + /// Optional. The release year of the book. + /// Optional. The path of the image representing the cover of the book. + /// Whether the release year should be included, or forced to . + /// Whether the cover path should be included, or forced to . + /// The created . + public BookLiteDto Create( + Guid? id = null, + string? title = null, + int? releaseYear = null, + string? coverPath = null, + bool includeReleaseYear = false, + bool includeCoverPath = false) + { + return new BookLiteDto + { + Id = id ?? _faker.Random.Guid(), + Title = title ?? _faker.Lorem.Sentence(3), + ReleaseYear = includeReleaseYear ? (releaseYear ?? _faker.Random.Int(1900, 2024)) : null, + CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs new file mode 100644 index 00000000..8419793d --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanJobProgressDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanJobProgressDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional number of completed items of the media library scan job. + /// Optional total number of items of the media library scan job. + /// Optional current operation being performed by the media library scan job. + /// Optional completion ratio of the media library scan job, as a percentage. + /// A configured instance. + public LibraryScanJobProgressDto Create( + int? completedItems = null, + int? totalItems = null, + string? currentOperation = null, + decimal? progressPercentage = null) + { + int completed = completedItems ?? _faker.Random.Int(0, 100); + int total = totalItems ?? _faker.Random.Int(completed, 100); + return new LibraryScanJobProgressDto + { + CompletedItems = completed, + TotalItems = total, + CurrentOperation = currentOperation ?? _faker.Hacker.Verb(), + ProgressPercentage = progressPercentage ?? (total > 0 ? (decimal)completed / total * 100 : 0) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs new file mode 100644 index 00000000..08af8992 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryScanProgressDtoFixture.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanProgressDtoFixture +{ + private readonly Faker _faker = new(); + + private readonly LibraryScanJobProgressDtoFixture _libraryScanJobProgressDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the media library scan. + /// Optional unique identifier of the user initiating the media library scan. + /// Optional unique identifier of the media library that is scanned. + /// Optional number of completed jobs of the media library scan job. + /// Optional total number of jobs of the media library scan job. + /// Optional status of the media library scan. + /// Whether the current job progress should be included, or forced to . + /// A configured instance. + public LibraryScanProgressDto Create( + Guid? scanId = null, + Guid? userId = null, + Guid? libraryId = null, + int? completedJobs = null, + int? totalJobs = null, + string? status = null, + bool includeCurrentJobProgress = false) + { + int completed = completedJobs ?? _faker.Random.Int(0, 10); + int total = totalJobs ?? _faker.Random.Int(completed, 10); + return new LibraryScanProgressDto + { + ScanId = scanId ?? Guid.NewGuid(), + UserId = userId ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid(), + CompletedJobs = completed, + TotalJobs = total, + CurrentJobProgress = includeCurrentJobProgress ? _libraryScanJobProgressDtoFixture.Create() : null, + Status = status ?? _faker.PickRandom("Running", "Completed", "Failed"), + OverallProgressPercentage = total > 0 ? (decimal)completed / total * 100 : 0 + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs new file mode 100644 index 00000000..8bf4938f --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/PaginatedBookLiteDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PaginatedBookLiteDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional collection of lightweight book elements. + /// Optional current page number in a paginated collection. + /// Optional number of items to include per page in paginated results. + /// Optional total number of elements available in the paginated result set. + /// Optional total number of pages based on the elements available and per page. + /// A configured instance. + public PaginatedBookLiteDto Create( + IReadOnlyList? data = null, + int? currentPage = null, + int? perPage = null, + int? count = null, + int? numberOfPages = null) + { + return new PaginatedBookLiteDto + { + Data = data ?? [], + CurrentPage = currentPage ?? _faker.Random.Int(1, 10), + PerPage = perPage ?? _faker.Random.Int(1, 100), + Count = count ?? _faker.Random.Int(0, 1000), + NumberOfPages = numberOfPages ?? _faker.Random.Int(1, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs new file mode 100644 index 00000000..5632286e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeLayoutPageDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeLayoutPageDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the page, displayed by the themed shell. + /// Optional. The rendered HTML content of the page section. + /// Optional. The rendered script element of the page section, when the template defines one. + /// The created . + public ThemeLayoutPageDto Create( + string? title = null, + string? content = null, + string? script = null) + { + return new ThemeLayoutPageDto( + title ?? _faker.Lorem.Word(), + content ?? _faker.Lorem.Paragraph(), + script ?? _faker.Lorem.Word()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs new file mode 100644 index 00000000..76cc62a7 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavEntryDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavEntryDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional label of the entry. + /// Optional URL of the link, or for a submenu. + /// Whether to set , or when . + /// Optional CSS classes of the link. + /// Whether to set , or when . + /// Optional child links of a submenu. + /// The created . + public ThemeNavEntryDto Create( + string? label = null, + string? url = null, + bool includeUrl = false, + string? cssClass = null, + bool includeCssClass = false, + IReadOnlyList? children = null) + { + return new ThemeNavEntryDto( + Label: label ?? _faker.Lorem.Word(), + Url: includeUrl ? (url ?? _faker.Internet.Url()) : null, + CssClass: includeCssClass ? (cssClass ?? _faker.Lorem.Word()) : null, + Children: children ?? []); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs new file mode 100644 index 00000000..348b85b0 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavSectionDtoFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ThemeNavSectionDtoFixture +{ + private readonly Faker _faker = new(); + private readonly ThemeNavEntryDtoFixture _themeNavEntryDtoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional label of the section. + /// Optional entries of the section. + /// The created . + public ThemeNavSectionDto Create( + string? label = null, + IReadOnlyList? items = null) + { + return new ThemeNavSectionDto( + Label: label ?? _faker.Lorem.Word(), + Items: items ?? [_themeNavEntryDtoFixture.Create()]); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs new file mode 100644 index 00000000..647af988 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageRenderResultDtoFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ThemePageRenderResultDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional rendered HTML content of the page section. + /// Optional rendered script element of the page section. + /// A configured instance. + public ThemePageRenderResultDto Create( + string? content = null, + string? script = null) + { + return new ThemePageRenderResultDto( + Content: content ?? _faker.Lorem.Paragraph(), + Script: script ?? _faker.Lorem.Paragraph() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs new file mode 100644 index 00000000..e6fb93e8 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UserDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user. + /// Optional username of the user. + /// A configured instance. + public UserDto Create( + Guid? id = null, + string? username = null) + { + return new UserDto( + Id: id ?? Guid.NewGuid(), + Username: username ?? _faker.Internet.UserName() + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs new file mode 100644 index 00000000..8c6d4dda --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateRoleRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the role. + /// Optional name of the role. + /// Optional collection of permission identifiers. + /// A configured instance. + public UpdateRoleRequest Create( + Guid? roleId = null, + string? roleName = null, + List? permissions = null) + { + return new UpdateRoleRequest( + RoleId: roleId ?? Guid.NewGuid(), + RoleName: roleName ?? _faker.Commerce.Department(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs new file mode 100644 index 00000000..b3f910af --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the user. + /// Optional identifier of the role assigned to the user. + /// Optional collection of permission identifiers assigned to the user. + /// A configured instance. + public UpdateUserRoleAndPermissionsRequest Create( + Guid? userId = null, + Guid? roleId = null, + List? permissions = null) + { + return new UpdateUserRoleAndPermissionsRequest( + UserId: userId ?? Guid.NewGuid(), + RoleId: roleId ?? Guid.NewGuid(), + Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs new file mode 100644 index 00000000..85ef74c6 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksViewRequestFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetBooksViewRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional unique identifier of the media library whose books are browsed. + /// A configured instance. + public GetBooksViewRequest Create( + Guid? libraryId = null) + { + return new GetBooksViewRequest( + LibraryId: libraryId + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs new file mode 100644 index 00000000..fdd4991b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/DeleteThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to delete. + /// A configured instance. + public DeleteThemeRequest Create( + string? themeId = null) + { + return new DeleteThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs new file mode 100644 index 00000000..2790427b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeArchiveRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetThemeArchiveRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to download. + /// A configured instance. + public GetThemeArchiveRequest Create( + string? themeId = null) + { + return new GetThemeArchiveRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs new file mode 100644 index 00000000..a0e2c25c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/GetThemeAssetRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetThemeAssetRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme. + /// Optional asset path relative to the theme pack root. + /// A configured instance. + public GetThemeAssetRequest Create( + string? themeId = null, + string? path = null) + { + return new GetThemeAssetRequest( + ThemeId: themeId, + Path: path + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs new file mode 100644 index 00000000..d90e2661 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/RestoreThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the bundled theme to restore. + /// A configured instance. + public RestoreThemeRequest Create( + string? themeId = null) + { + return new RestoreThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs new file mode 100644 index 00000000..9da2f514 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Themes/SetCurrentThemeRequestFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeRequestFixture +{ + /// + /// Creates a new instance. + /// + /// Optional manifest id of the theme to activate. + /// A configured instance. + public SetCurrentThemeRequest Create( + string? themeId = null) + { + return new SetCurrentThemeRequest( + ThemeId: themeId + ); + } + + /// + /// Creates multiple instances. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs new file mode 100644 index 00000000..e6f47bde --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/Authorization/GetAuthorizationResponseFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class GetAuthorizationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the user. + /// Optional role associated to the user. + /// Optional collection of permissions associated to the user. + /// A configured instance. + public GetAuthorizationResponse Create( + Guid? userId = null, + string? role = null, + AuthorizationPermission[]? permissions = null) + { + return new GetAuthorizationResponse( + UserId: userId ?? Guid.NewGuid(), + Role: role ?? _faker.Name.JobTitle(), + Permissions: permissions ?? [AuthorizationPermission.CanViewUsers] + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs new file mode 100644 index 00000000..2144d5b3 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/ChangePasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was changed or not. + /// The created . + public ChangePasswordResponse Create( + bool? isPasswordChanged = null) + { + return new ChangePasswordResponse(isPasswordChanged ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs new file mode 100644 index 00000000..ccd88f54 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RecoverPasswordResponseFixture.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. Whether the password was reset or not. + /// The created . + public RecoverPasswordResponse Create( + bool? isPasswordReset = null) + { + return new RecoverPasswordResponse(isPasswordReset ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs new file mode 100644 index 00000000..da00e31c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Responses/UsersManagement/RegisterResponseFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class RegisterResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional username of the registered user. + /// Optional TOTP secret used for two-factor authentication. + /// A configured instance. + public RegisterResponse Create( + string? username = null, + string? totpSecret = null) + { + return new RegisterResponse( + Username: username ?? _faker.Internet.UserName(), + TotpSecret: totpSecret ?? _faker.Random.AlphaNumeric(16) + ); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..bc029b1f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-create-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardRoleAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..963ad8f2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardDeleteAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + string expectedEndpoint = $"auth/roles/{roleId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == expectedEndpoint); + } + + [Fact] + public async Task DeleteRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + Guid roleId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs new file mode 100644 index 00000000..50c497e1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolePermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnRolePermissionsJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + RolePermissionsDto expectedResponse = _rolePermissionsDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/roles/{roleId}/permissions", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-role-id/{roleId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedResponse.Permissions.Length, json.RootElement.GetProperty("data").GetProperty("permissions").GetArrayLength()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs new file mode 100644 index 00000000..34b80bc2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-update-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateRole_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPutResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs new file mode 100644 index 00000000..def9fd02 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManagePermissions; + +/// +/// Contains integration tests for the /{culture}/admin/manage-permissions route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManagePermissionsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly UserDtoFixture _userDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManagePermissionsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManagePermissions_WhenCalledByAuthenticatedAdmin_ShouldRenderPermissionsManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany()]; + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/users", expectedUsers); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs new file mode 100644 index 00000000..53bf006b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.ManageRoles; + +/// +/// Contains integration tests for the /{culture}/admin/manage-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManageRolesViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManageRolesViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManageRoles_WhenCalledByAuthenticatedAdmin_ShouldRenderRolesManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } + + [Fact] + public async Task ManageRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..1078a03c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldDeleteThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"themes/{THEME_ID}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/themes/api-delete-theme/{THEME_ID}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"themes/{THEME_ID}"); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, "/en-us/admin/themes/api-delete-theme/%20") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..a4f93086 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DownloadThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DownloadTheme_WhenCalledByAuthenticatedAdmin_ShouldReturnThemeArchive() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x50, 0x4B, 0x03, 0x04, 0x01, 0x02]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "application/zip")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/test-theme"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/zip", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Fact] + public async Task DownloadTheme_WhenCalledWithEmptyThemeId_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/%20"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(downloadRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..38c8b797 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetThemesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetThemes_WhenCalledByAuthenticatedAdmin_ShouldReturnThemesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()]; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme"); + ThemeSettingsResponseDto expectedSettings = _themeSettingsResponseDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/settings", expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-get-themes"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(expectedThemes.Length, data.GetProperty("themes").GetArrayLength()); + Assert.Equal("current-theme", data.GetProperty("currentThemeId").GetString()); + Assert.Equal(expectedSettings.MaxArchiveBytes, data.GetProperty("maxArchiveBytes").GetInt64()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/settings"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..ea838726 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public InstallThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task InstallTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUploadAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string fileName = "theme.zip"; + _apiFactory.ApiClientStub.RegisterPostResponse("themes", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent(fileName) + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + installRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes" && postRequest.Data as string == fileName); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + /// + /// Builds a multipart form content carrying a single file part. + /// + /// The name of the uploaded file. + /// The multipart form content. + private static MultipartFormDataContent CreateMultipartContent(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new([0x50, 0x4B, 0x03, 0x04]); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + form.Add(fileContent, "archive", fileName); + return form; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..37b2a082 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldRestoreThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterPostResponse($"themes/{THEME_ID}/restore", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{THEME_ID}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"themes/{THEME_ID}/restore"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..ec36ed94 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes.SetCurrentTheme; + +/// +/// Contains integration tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetCurrentThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldSetCurrentThemeAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + const string THEME_ID = "test-theme"; + _apiFactory.ApiClientStub.RegisterPutResponse("themes/current", _themeResponseDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") + { + Content = JsonContent.Create(new SetCurrentThemeRequest(THEME_ID)) + }; + setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + setCurrentThemeRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(setCurrentThemeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "themes/current"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..f9ab2759 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.Themes; + +/// +/// Contains integration tests for the /{culture}/admin/manage-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemesIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderThemesManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ThemeResponseDto[] expectedThemes = [.. _themeResponseDtoFixture.CreateMany()]; + ThemeResponseDto currentTheme = _themeResponseDtoFixture.Create(themeId: "current-theme"); + _apiFactory.ApiClientStub.RegisterGetResponse("themes", expectedThemes); + _apiFactory.ApiClientStub.RegisterGetResponse("themes/current", currentTheme); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-themes"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes/current"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs new file mode 100644 index 00000000..781e3dd4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByAuthenticatedAdmin_ShouldReturnUserPermissionsJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-permissions-by-user-id/{userId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedPermissions.Length, json.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs new file mode 100644 index 00000000..d2dab495 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// Contains integration tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserRole_WhenCalledByAuthenticatedAdmin_ShouldReturnUserRoleJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + RoleDto expectedRole = _roleDtoFixture.Create(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/role", expectedRole); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/api-get-role-by-user-id/{userId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedRole.RoleName, json.RootElement.GetProperty("data").GetProperty("roleName").GetString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs new file mode 100644 index 00000000..90843ed4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Contains integration tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserRoleAndPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByAuthenticatedAdminWithAntiforgeryToken_ShouldForwardUpdateAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); + string expectedEndpoint = $"auth/users/{request.UserId}/role-and-permissions"; + GetAuthorizationResponse expectedResponse = _getAuthorizationResponseFixture.Create(userId: request.UserId); + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..c1ff40b9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains integration tests for the /directories/api-get-directories route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly DirectoryDtoFixture _directoryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDirectoriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDirectories_WhenCalledByAuthenticatedUser_ShouldReturnDirectoriesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: path, name: "test")]; + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedDirectories); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedDirectories.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..07c7e66c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// Contains integration tests for the /drives/api-get-drives route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDrivesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDrives_WhenCalledByAuthenticatedUser_ShouldReturnDrivesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + FileSystemTreeNodeDto[] expectedDrives = [_fileSystemTreeNodeDtoFixture.Create(path: "C:\\", name: "C:")]; + _apiFactory.ApiClientStub.RegisterGetResponse("drives/get-drives", expectedDrives); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/drives/api-get-drives"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedDrives.Length, json.RootElement.GetProperty("data").GetProperty("drives").GetArrayLength()); + Assert.Contains("drives/get-drives", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs new file mode 100644 index 00000000..f2153bc0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Enums.FileSystem; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// Contains integration tests for the /file-system/api-get-type route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTypeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTypeDtoFixture _fileSystemTypeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTypeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetType_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTypeFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("file-system/get-type", _fileSystemTypeDtoFixture.Create(platformType: PlatformType.Windows)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/file-system/api-get-type"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(nameof(PlatformType.Windows), json.RootElement.GetProperty("data").GetProperty("platformType").GetString()); + Assert.Contains("file-system/get-type", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs new file mode 100644 index 00000000..cc2ccee9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Contains integration tests for the /files/api-get-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileDtoFixture _fileDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetFiles_WhenCalledByAuthenticatedUser_ShouldReturnFilesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + FileDto[] expectedFiles = [_fileDtoFixture.Create(path: path, name: "book.pdf")]; + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedFiles); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedFiles.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..b391ad50 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Contains integration tests for the /files/api-get-tree-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly FileSystemTreeNodeDtoFixture _fileSystemTreeNodeDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTreeFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetTreeFiles_WhenCalledByAuthenticatedUser_ShouldReturnFileSystemTreeFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + FileSystemTreeNodeDto[] expectedNodes = [_fileSystemTreeNodeDtoFixture.Create(path: path, name: "test")]; + string expectedEndpoint = $"files/get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedNodes); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-tree-files?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedNodes.Length, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..835e0471 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Contains integration tests for the /path/api-check-path-exists route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathExistsDtoFixture _pathExistsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CheckPathExistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CheckPathExists_WhenCalledByAuthenticatedUser_ShouldReturnExistenceFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create(exists: true)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(path)}&includeHiddenElements=true"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("exists").GetBoolean()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..f3c3d81e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Contains integration tests for the /path/api-get-path-parent route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathParentEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathParent_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + PathSegmentDto[] expectedSegments = [_pathSegmentDtoFixture.Create(path: @"C:\Users")]; + string expectedEndpoint = $"path/get-path-parent?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-parent?path={Uri.EscapeDataString(path)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..5aa67b41 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Contains integration tests for the /path/api-get-path-root route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathRootEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathRoot_WhenCalledByAuthenticatedUser_ShouldReturnPathRootFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/get-path-root?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathSegmentDtoFixture.Create(path: @"C:\")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-root?path={Uri.EscapeDataString(path)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(@"C:\", json.RootElement.GetProperty("data").GetProperty("root").GetProperty("path").GetString()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..c3d971da --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Contains integration tests for the /path/api-get-path-separator route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSeparatorDtoFixture _pathSeparatorDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathSeparatorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathSeparator_WhenCalledByAuthenticatedUser_ShouldReturnPathSeparatorFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedSeparator = "\\"; + _apiFactory.ApiClientStub.RegisterGetResponse("path/get-path-separator", _pathSeparatorDtoFixture.Create(separator: expectedSeparator)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/path/api-get-path-separator"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedSeparator, json.RootElement.GetProperty("data").GetProperty("pathSeparator").GetString()); + Assert.Contains("path/get-path-separator", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs new file mode 100644 index 00000000..9099673a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Contains integration tests for the /path/api-split route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SplitPathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SplitPath_WhenCalledByAuthenticatedUser_ShouldReturnPathSegmentsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + PathSegmentDto[] expectedSegments = + [ + _pathSegmentDtoFixture.Create(path: @"C:\"), + _pathSegmentDtoFixture.Create(path: "Users"), + _pathSegmentDtoFixture.Create(path: "test") + ]; + string expectedEndpoint = $"path/split?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSegments); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-split?path={Uri.EscapeDataString(path)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedSegments.Length, json.RootElement.GetProperty("data").GetProperty("pathSegments").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..01313cdc --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains integration tests for the /path/api-validate route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathValidDtoFixture _pathValidDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ValidatePathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ValidatePath_WhenCalledByAuthenticatedUser_ShouldReturnValidityFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string path = @"C:\Users\test"; + string expectedEndpoint = $"path/validate?path={Uri.EscapeDataString(path)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathValidDtoFixture.Create(isValid: true)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-validate?path={Uri.EscapeDataString(path)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isValid").GetBoolean()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs new file mode 100644 index 00000000..60fab458 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/error route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeErrorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeErrorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeError_WhenCalledByAuthenticatedUser_ShouldRenderErrorPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/error"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("text-danger", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs new file mode 100644 index 00000000..09b1028f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/not-found route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeNotFoundViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeNotFoundViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeNotFoundView_WhenCalledByAuthenticatedUser_ShouldRenderNotFoundPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/not-found"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs new file mode 100644 index 00000000..86ca4fb6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Home; + +/// +/// Contains integration tests for the /{culture}/privacy route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomePrivacyEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomePrivacyEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomePrivacy_WhenCalledByAuthenticatedUser_ShouldRenderPrivacyPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/privacy"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("Privacy Policy", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs new file mode 100644 index 00000000..63ef8b49 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryAddingView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..7e85cdb0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibrariesScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScansAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostResponseFactory("libraries/scans/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest("/en-us/libraries/manage/api-cancel-libraries-scan"); + cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..93b3b4aa --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibraryScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldCancelScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponseFactory($"libraries/{libraryId}/scans/{scanId}/cancel", _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + cancelRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..16c5b86f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldDeleteLibraryAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}"); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(libraryId); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } + + /// + /// Builds the delete request for the library identified by . + /// + /// The Id of the library to delete. + /// The configured delete request. + private static HttpRequestMessage CreateDeleteRequest(Guid libraryId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}") + { + // the front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs new file mode 100644 index 00000000..08ea87d2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.EditLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditLibraryView_WhenCalledByAuthenticatedUser_ShouldRenderLibraryEditingView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books", libraryType: "Book"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..028e6e65 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetEnabledLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalledByAuthenticatedUser_ShouldReturnEnabledLibrariesJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryDto[] expectedLibraries = + [ + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"), + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video") + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", expectedLibraries); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetArrayLength()); + Assert.Equal("Books", data[0].GetProperty("title").GetString()); + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalled_ShouldRequestEnabledLibrariesFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/enabled", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries/enabled", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..7ff6e394 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetMetadataProviders; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryMetadataProviderDtoFixture _libraryMetadataProviderDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetMetadataProviders_WhenCalledByAuthenticatedUser_ShouldReturnMetadataProvidersJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderDto[] expectedProviders = + [ + _libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider One", isEnabled: true, rank: 1), + _libraryMetadataProviderDtoFixture.Create(name: "Metadata Provider Two", isEnabled: false, rank: 2) + ]; + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", expectedProviders); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetArrayLength()); + Assert.Equal("Metadata Provider One", data[0].GetProperty("name").GetString()); + } + + [Fact] + public async Task GetMetadataProviders_WhenCalled_ShouldRequestMetadataProvidersFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/metadata-providers", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains($"libraries/{libraryId}/metadata-providers", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..4d1fcea0 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,82 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryScanProgressDtoFixture _libraryScanProgressDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRunningLibraryScansEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalledByAuthenticatedUser_ShouldReturnRunningLibraryScansJson() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + LibraryScanProgressDto[] expectedScans = + [ + _libraryScanProgressDtoFixture.Create(includeCurrentJobProgress: true), + _libraryScanProgressDtoFixture.Create() + ]; + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", expectedScans); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(2, data.GetArrayLength()); + Assert.Equal(JsonValueKind.Object, data[0].GetProperty("currentJobProgress").ValueKind); + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalled_ShouldRequestRunningLibraryScansFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("libraries/scans/running", Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("libraries/scans/running", _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs new file mode 100644 index 00000000..e36f0c3d --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.Index; + +/// +/// Contains integration tests for the /{culture}/libraries/manage route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LibrariesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LibrariesIndexView_WhenCalledByAuthenticatedUser_ShouldRenderLibrariesManagementView() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/libraries/manage"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..6765f340 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-reorder-metadata-providers route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ReorderMetadataProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( + libraryId: libraryId, + pluginIds: [firstPluginId, secondPluginId] + ); + string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/reorder"; + _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..f9dda266 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibraries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + ScanLibraryDto[] expectedScans = + [ + _scanLibraryDtoFixture.Create(libraryId: libraryId) + ]; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries/scans", expectedScans); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest("/en-us/libraries/manage/api-scan-libraries"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(1, json.RootElement.GetProperty("data").GetArrayLength()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..e615d08e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ScanLibraryDtoFixture _scanLibraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibrary_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldInitiateScanAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + ScanLibraryDto expectedScan = _scanLibraryDtoFixture.Create(libraryId: libraryId); + _apiFactory.ApiClientStub.RegisterPostResponse($"libraries/{libraryId}/scans", expectedScan); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(libraryId, json.RootElement.GetProperty("data").GetProperty("libraryId").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..093e89a2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; + +/// +/// Contains integration tests for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetMetadataProviderEnabledEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetMetadataProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( + libraryId: libraryId, + pluginId: pluginId, + isEnabled: true + ); + string expectedEndpoint = $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; + _apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs new file mode 100644 index 00000000..6d694754 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditBookViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditBookViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditBook_WhenCalledByAuthenticatedUser_ShouldRenderEditBookPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("A book", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..3e3ac35e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PaginatedBookLiteDtoFixture _paginatedBookLiteDtoFixture = new(); + private readonly BookLiteDtoFixture _bookLiteDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryItemsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryItems_WhenCalledByAuthenticatedUser_ShouldReturnBooksFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string searchTerm = "Harry"; + PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create(data: [_bookLiteDtoFixture.Create(title: "Harry Potter")]); + string expectedEndpoint = $"books/lite?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=True"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}¤tPage=1&perPage=20&searchTerm={searchTerm}&shouldIgnoreThePrefixForAlphaPicker=true"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(expectedResponse.Data.Count, json.RootElement.GetProperty("data").GetProperty("data").GetArrayLength()); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..2661e493 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains integration tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public BooksIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task BooksIndex_WhenCalledByAuthenticatedUserWithLibraryId_ShouldRenderBooksPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + LibraryDto expectedLibrary = _libraryDtoFixture.Create(id: libraryId, title: "Books"); + _apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}", expectedLibrary); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/library/written-content-library/books-library/books?libraryId={libraryId}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("search-input", content); + Assert.Contains($"libraries/{libraryId}", _apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task BooksIndex_WhenCalledByAuthenticatedUserWithoutLibraryId_ShouldRedirectToHome() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/library/written-content-library/books-library/books"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..65bcc2b6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// Contains integration tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PluginSettingsDtoFixture _pluginSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPluginSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPluginSettings_WhenCalledByAuthenticatedAdmin_ShouldReturnPluginSettingsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid pluginId = Guid.NewGuid(); + PluginSettingsDto expectedSettings = _pluginSettingsDtoFixture.Create(pluginId: pluginId); + string expectedEndpoint = $"plugins/{pluginId}/settings"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{pluginId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(pluginId, json.RootElement.GetProperty("data").GetProperty("pluginId").GetGuid()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == expectedEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs new file mode 100644 index 00000000..01346b29 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Plugins.Index; + +/// +/// Contains integration tests for the /{culture}/admin/manage-plugins route served by the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PluginDtoFixture _pluginDtoFixture = new(); + private readonly PluginSettingsDtoFixture _pluginSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PluginsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task PluginsIndex_WhenCalledByAuthenticatedAdmin_ShouldRenderPluginsManagementPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + PluginDto[] expectedPlugins = [_pluginDtoFixture.Create(name: "OpenLibrary")]; + string settingsEndpoint = $"plugins/{expectedPlugins[0].Id}/settings"; + _apiFactory.ApiClientStub.RegisterGetResponse("plugins", expectedPlugins); + _apiFactory.ApiClientStub.RegisterGetResponse(settingsEndpoint, _pluginSettingsDtoFixture.Create(pluginId: expectedPlugins[0].Id)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-plugins"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "plugins"); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == settingsEndpoint); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..f5801bd9 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Contains integration tests for the /theme-assets/{themeId}/{path} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemeAssetsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithValidThemeAndPath_ShouldReturnAsset() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage assetRequest = new(HttpMethod.Get, "/theme-assets/test-theme/assets/logo.png"); + assetRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(assetRequest); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("image/png", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithEmptyPath_ShouldReturnBadRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/theme-assets/test-theme/"); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs new file mode 100644 index 00000000..751b5e03 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.AccessDenied; + +/// +/// Contains integration tests for the /{culture}/auth/access-denied route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AccessDeniedViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AccessDeniedViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AccessDeniedView_WhenCalled_ShouldRenderAccessDeniedPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/access-denied"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..88dea4da --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains integration tests for the /{culture}/auth/api-change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly ChangePasswordResponseFixture _changePasswordResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePassword_WhenCalledByAuthenticatedUser_ShouldChangePasswordForCurrentUser() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + ChangePasswordResponse expectedResponse = _changePasswordResponseFixture.Create(isPasswordChanged: true); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/change-password", expectedResponse); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(currentPassword: "OldPass123!", newPassword: "NewPass123!", newPasswordConfirm: "NewPass123!"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + (string Endpoint, object? Data) postRequest = _apiFactory.ApiClientStub.PostRequests.Single(postRequest => postRequest.Endpoint == "auth/change-password"); + ChangePasswordRequest sentRequest = Assert.IsType(postRequest.Data); + Assert.Equal("testuser", sentRequest.Username); + } + + /// + /// Builds the change password request that sends the given to the change password endpoint. + /// + /// The change password request to send. + /// The antiforgery token to include in the request. + /// The configured change password request. + private static HttpRequestMessage CreateChangePasswordRequest(ChangePasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return changePasswordRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs new file mode 100644 index 00000000..c82a4497 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains integration tests for the /{culture}/auth/change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePasswordView_WhenCalledByAuthenticatedUser_ShouldRenderChangePasswordPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/auth/change-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("change-password-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs new file mode 100644 index 00000000..b0457f9e --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Logout; + +/// +/// Contains integration tests for the /{culture}/auth/logout route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LogoutEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LogoutEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Logout_WhenCalledByAuthenticatedUser_ShouldSignOutAndRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/auth/logout"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..dd0909c4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains integration tests for the /{culture}/auth/api-recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly RecoverPasswordResponseFixture _recoverPasswordResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPassword_WhenCalledWithValidData_ShouldResetPassword() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RecoverPasswordResponse expectedResponse = _recoverPasswordResponseFixture.Create(isPasswordReset: true); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/recover-password", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isPasswordReset").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/recover-password"); + } + + /// + /// Builds the recover password request that sends the given to the recover password endpoint. + /// + /// The recover password request to send. + /// The antiforgery token to include in the request. + /// The configured recover password request. + private static HttpRequestMessage CreateRecoverPasswordRequest(RecoverPasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + recoverPasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + recoverPasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return recoverPasswordRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs new file mode 100644 index 00000000..be8a1c62 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains integration tests for the /{culture}/auth/recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPasswordView_WhenCalled_ShouldRenderRecoverPasswordPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/recover-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("recover-password-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..4a23234f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains integration tests for the /{culture}/auth/api-register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + private readonly RegisterResponseFixture _registerResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Register_WhenCalledWithValidData_ShouldRegisterAccount() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RegisterResponse expectedResponse = _registerResponseFixture.Create(username: "newuser"); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/register", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("newuser", json.RootElement.GetProperty("data").GetProperty("username").GetString()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/register"); + } + + [Fact] + public async Task Register_WhenRegistrationTypeIsAdmin_ShouldCallInitializationEndpoint() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + RegisterResponse expectedResponse = _registerResponseFixture.Create(username: "admin"); + _apiFactory.ApiClientStub.RegisterPostResponse("initialization", expectedResponse); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "admin", password: "Abcd123$", passwordConfirm: "Abcd123$", registrationType: "Admin"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "initialization"); + } + + /// + /// Builds the register request that sends the given to the register endpoint. + /// + /// The register request to send. + /// The antiforgery token to include in the request. + /// The configured register request. + private static HttpRequestMessage CreateRegisterRequest(RegisterRequest request, string antiforgeryToken) + { + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + registerRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + registerRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return registerRequest; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs new file mode 100644 index 00000000..ccc43887 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains integration tests for the /{culture}/auth/register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RegisterView_WhenCalled_ShouldRenderRegisterPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/register"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("register-account-form", content); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs new file mode 100644 index 00000000..a60be659 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains security tests for the /initialization route. +/// +[ExcludeFromCodeCoverage] +public class CheckInitializationEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckInitializationEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task CheckInitialization_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/initialization"); + + // Assert + // the initialization check is anonymous, so it must never demand authentication or leak any internal data + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs new file mode 100644 index 00000000..c6235d7d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance.ApplicationSetup; + +/// +/// Contains security tests for the /initialization route. +/// +[ExcludeFromCodeCoverage] +public class SetupApplicationEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetupApplicationEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task SetupApplication_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Arrange + RegistrationRequest request = _registrationRequestFixture.Create( + username: $"testuser_{Guid.NewGuid()}", + password: "TestPass123!", + passwordConfirm: "TestPass123!", + use2fa: false + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the setup endpoint is anonymous, so it must never demand authentication; the admin account is created once, so + // the request either creates it or reports that it already exists, depending on the shared database state of the class + Assert.True(response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.Conflict); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + public async Task SetupApplication_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + // note: the setup validator only checks that the username is not empty, so the malicious value reaches the handler, + // where it is used as a literal username in parameterized queries; the security guarantee is that it never + // executes as SQL or leaks the query internals + RegistrationRequest request = _registrationRequestFixture.Create( + username: maliciousUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!", + use2fa: false + ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/initialization", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the malicious username is treated as literal data (the setup either creates the admin or reports that one already exists), + // so the request must never fail with an unhandled exception or leak the query internals + Assert.True(response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.Conflict); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs new file mode 100644 index 00000000..6de8855b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.AddRole; + +/// +/// Contains security tests for the /{culture}/admin/api-create-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task AddRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(_addRoleRequestFixture.Create()) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddRole_WithInjectionInRoleName_ShouldRemainSecure(string maliciousRoleName) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AddRoleRequest request = _addRoleRequestFixture.Create(roleName: maliciousRoleName); + _apiFactory.ApiClientStub.RegisterPostResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/admin/api-create-role") + { + Content = JsonContent.Create(request) + }; + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs new file mode 100644 index 00000000..fb2ed8cf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; + +/// +/// Contains security tests for the /{culture}/admin/api-delete-role/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid roleId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(roleId); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"auth/roles/{roleId}"); + } + + [Fact] + public async Task DeleteRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid roleId = Guid.NewGuid(); + HttpRequestMessage deleteRequest = CreateDeleteRequest(roleId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"auth/roles/{roleId}"); + } + + [Fact] + public async Task DeleteRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid()); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task DeleteRole_WithInjectionInRoleId_ShouldRemainSecure(string maliciousRoleId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{Uri.EscapeDataString(maliciousRoleId)}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled); + } + + /// + /// Builds a DELETE request for the role deletion route with the JSON content type required by the antiforgery validation. + /// + /// The identifier of the role to delete. + /// The configured DELETE request. + private static HttpRequestMessage CreateDeleteRequest(Guid roleId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/api-delete-role/{roleId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs new file mode 100644 index 00000000..9da9e71a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRolePermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-get-permissions-by-role-id/{roleId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRolePermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRolePermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetRolePermissions_WhenCalledByAdminUser_ShouldReturnRolePermissionsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid roleId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/roles/{roleId}/permissions", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-role-id/" + roleId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs new file mode 100644 index 00000000..1cd600ba --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.UpdateRole; + +/// +/// Contains security tests for the /{culture}/admin/api-update-role route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "auth/roles"); + } + + [Fact] + public async Task UpdateRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(_updateRoleRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateRole_WithInjectionInRoleName_ShouldRemainSecure(string maliciousRoleName) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: maliciousRoleName); + _apiFactory.ApiClientStub.RegisterPutResponse("auth/roles", _rolePermissionsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-role") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs new file mode 100644 index 00000000..2730d614 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManagePermissions/ManagePermissionsViewEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManagePermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManagePermissions; + +/// +/// Contains security tests for the /{culture}/admin/manage-permissions route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManagePermissionsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly UserDtoFixture _userDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManagePermissionsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManagePermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "auth/users"); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task ManagePermissions_WhenCalledByAdminUser_ShouldReturnPermissionsPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany()]; + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/users", expectedUsers); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-permissions"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs new file mode 100644 index 00000000..9e28575c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/ManageRoles/ManageRolesViewEndpointTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.ManageRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.ManageRoles; + +/// +/// Contains security tests for the /{culture}/admin/manage-roles route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ManageRolesViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ManageRolesViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ManageRoles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "auth/roles"); + } + + [Fact] + public async Task ManageRoles_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task ManageRoles_WhenCalledByAdminUser_ShouldReturnRolesPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [.. _roleDtoFixture.CreateMany()]; + PermissionDto[] expectedPermissions = [.. _permissionDtoFixture.CreateMany()]; + _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); + _apiFactory.ApiClientStub.RegisterGetResponse("auth/permissions", expectedPermissions); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/manage-roles"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs new file mode 100644 index 00000000..298207ca --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.DeleteTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-delete-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeleteThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage deleteRequest = CreateDeleteRequest("test-theme"); + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == "themes/test-theme"); + } + + [Fact] + public async Task DeleteTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest("test-theme"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == "themes/test-theme"); + } + + /// + /// Builds a DELETE request for the theme deletion route with the JSON content type required by the antiforgery validation. + /// + /// The manifest id of the theme to delete. + /// The configured DELETE request. + private static HttpRequestMessage CreateDeleteRequest(string themeId) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/admin/themes/api-delete-theme/{themeId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return deleteRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs new file mode 100644 index 00000000..846c8c05 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.DownloadTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-download-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class DownloadThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DownloadThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DownloadTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage downloadRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-download-theme/test-theme"); + downloadRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(downloadRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs new file mode 100644 index 00000000..b50c4f80 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/GetThemes/GetThemesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.GetThemes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.GetThemes; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-get-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetThemesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetThemesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetThemes_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/themes/api-get-themes"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs new file mode 100644 index 00000000..7e232089 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/InstallTheme/InstallThemeEndpointTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.InstallTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.InstallTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-install-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class InstallThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public InstallThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + [Fact] + public async Task InstallTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/themes/api-install-theme") + { + Content = CreateMultipartContent("theme.zip") + }; + installRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(installRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes"); + } + + /// + /// Builds a multipart form content carrying a single file part. + /// + /// The name of the uploaded file. + /// The multipart form content. + private static MultipartFormDataContent CreateMultipartContent(string fileName) + { + MultipartFormDataContent form = []; + ByteArrayContent fileContent = new([0x50, 0x4B, 0x03, 0x04]); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + form.Add(fileContent, "archive", fileName); + return form; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs new file mode 100644 index 00000000..93238c02 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.RestoreTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-restore-theme/{themeId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RestoreThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RestoreThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage restoreRequest = CreateRestoreRequest("test-theme"); + restoreRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes/test-theme/restore"); + } + + [Fact] + public async Task RestoreTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage restoreRequest = CreateRestoreRequest("test-theme"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "themes/test-theme/restore"); + } + + /// + /// Builds a POST request for the theme restore route with the JSON content type required by the antiforgery validation. + /// + /// The manifest id of the bundled theme to restore. + /// The configured POST request. + private static HttpRequestMessage CreateRestoreRequest(string themeId) + { + HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/admin/themes/api-restore-theme/{themeId}") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return restoreRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs new file mode 100644 index 00000000..6d790938 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Themes; +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes.SetCurrentTheme; + +/// +/// Contains security tests for the /{culture}/admin/themes/api-set-current-theme route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetCurrentThemeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetCurrentThemeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage setCurrentThemeRequest = CreateSetCurrentThemeRequest(); + setCurrentThemeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(setCurrentThemeRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "themes/current"); + } + + [Fact] + public async Task SetCurrentTheme_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage setCurrentThemeRequest = CreateSetCurrentThemeRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(setCurrentThemeRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "themes/current"); + } + + /// + /// Builds a PUT request for the set current theme route with the JSON content type required by the antiforgery validation. + /// + /// The configured PUT request. + private static HttpRequestMessage CreateSetCurrentThemeRequest() + { + HttpRequestMessage setCurrentThemeRequest = new(HttpMethod.Put, "/en-us/admin/themes/api-set-current-theme") + { + Content = JsonContent.Create(new SetCurrentThemeRequest("test-theme")) + }; + setCurrentThemeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + setCurrentThemeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return setCurrentThemeRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs new file mode 100644 index 00000000..bf2c0de5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Themes/ThemesIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Themes; + +/// +/// Contains security tests for the /{culture}/admin/manage-themes route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemesIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-themes"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "themes"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs new file mode 100644 index 00000000..4463b697 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Authorization; +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserPermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-get-permissions-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserPermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserPermissions_WhenCalledByAdminUser_ShouldReturnUserPermissionsData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/permissions", new PermissionDto[] { _permissionDtoFixture.Create() }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-permissions-by-user-id/" + userId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs new file mode 100644 index 00000000..ac609df2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.GetUserRole; + +/// +/// Contains security tests for the /{culture}/admin/api-get-role-by-user-id/{userId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserRoleEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserRole_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("auth/login", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + Guid.NewGuid()); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Fact] + public async Task GetUserRole_WhenCalledByAdminUser_ShouldReturnUserRoleData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + Guid userId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterGetResponse($"auth/users/{userId}/role", _roleDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/admin/api-get-role-by-user-id/" + userId); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs new file mode 100644 index 00000000..befdd67e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.UsersManagement.Authorization.UpdateUserRoleAndPermissions; + +/// +/// Contains security tests for the /{culture}/admin/api-update-user-authorization route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserRoleAndPermissionsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("auth/users/", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint.StartsWith("auth/users/", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task UpdateUserRoleAndPermissions_WhenCalledByNonAdminUser_ShouldRedirectToAccessDenied() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = JsonContent.Create(_updateUserRoleAndPermissionsRequestFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Contains("access-denied", response.Headers.Location!.ToString()); + } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateUserRoleAndPermissions_WithInjectionInRoleId_ShouldRemainSecure(string maliciousRoleId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + string jsonBody = $"{{\"userId\":\"{Guid.NewGuid()}\",\"roleId\":\"{maliciousRoleId}\",\"permissions\":[]}}"; + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/api-update-user-authorization") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.Empty(_apiFactory.ApiClientStub.PutRequests); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs new file mode 100644 index 00000000..789cf711 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; + +/// +/// Contains security tests for the /directories/api-get-directories route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDirectoriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDirectories_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/directories/api-get-directories"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("directories/get-directories", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Directories--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetDirectories_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"directories/get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/directories/api-get-directories?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs new file mode 100644 index 00000000..3f8b7848 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Drives/GetDrives/GetDrivesEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Drives.GetDrives; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Drives.GetDrives; + +/// +/// Contains security tests for the /drives/api-get-drives route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetDrivesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetDrivesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetDrives_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/drives/api-get-drives"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "drives/get-drives"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs new file mode 100644 index 00000000..3974eea3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/FileSystem/GetType/GetTypeEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.FileSystem.GetType; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.FileSystem.GetType; + +/// +/// Contains security tests for the /file-system/api-get-type route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTypeEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTypeEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetType_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/file-system/api-get-type"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "file-system/get-type"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs new file mode 100644 index 00000000..82d98650 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetFiles/GetFilesEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetFiles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Files.GetFiles; + +/// +/// Contains security tests for the /files/api-get-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetFiles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/files/api-get-files"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("files/get-files", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Files--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetFiles_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"files/get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/files/api-get-files?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs new file mode 100644 index 00000000..fb4dbeaf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFiles/GetTreeFilesEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles; + +/// +/// Contains security tests for the /files/api-get-tree-files route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetTreeFilesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetTreeFiles_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/files/api-get-tree-files"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("files/get-tree-files", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs new file mode 100644 index 00000000..a4d3b46a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExists/CheckPathExistsEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.CheckPathExists; + +/// +/// Contains security tests for the /path/api-check-path-exists route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathExistsDtoFixture _pathExistsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CheckPathExistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CheckPathExists_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-check-path-exists"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("path/check-path-exists", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task CheckPathExists_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathExistsDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-check-path-exists?path={Uri.EscapeDataString(maliciousPath)}&includeHiddenElements=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs new file mode 100644 index 00000000..9b24a184 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathParent/GetPathParentEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathParent; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathParent; + +/// +/// Contains security tests for the /path/api-get-path-parent route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathParentEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathParent_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-parent"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("path/get-path-parent", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetPathParent_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/get-path-parent?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-parent?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs new file mode 100644 index 00000000..772f7cdc --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathRoot/GetPathRootEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathRoot; + +/// +/// Contains security tests for the /path/api-get-path-root route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathSegmentDtoFixture _pathSegmentDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathRootEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathRoot_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-root"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("path/get-path-root", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetPathRoot_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/get-path-root?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathSegmentDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-get-path-root?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs new file mode 100644 index 00000000..6a7666c1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparator/GetPathSeparatorEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator; + +/// +/// Contains security tests for the /path/api-get-path-separator route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPathSeparatorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPathSeparatorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPathSeparator_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-get-path-separator"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "path/get-path-separator"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs new file mode 100644 index 00000000..cd358c66 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/SplitPath/SplitPathEndpointTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.SplitPath; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.SplitPath; + +/// +/// Contains security tests for the /path/api-split route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SplitPathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SplitPathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SplitPath_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-split"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("path/split", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task SplitPath_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/split?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-split?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs new file mode 100644 index 00000000..19a5fb43 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.FileSystemManagement.Path.ValidatePath; + +/// +/// Contains security tests for the /path/api-validate route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PathValidDtoFixture _pathValidDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ValidatePathEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ValidatePath_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/path/api-validate"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("path/validate", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Paths--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task ValidatePath_WhenCalledWithInjectionInPath_ShouldRemainSecure(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"path/validate?path={Uri.EscapeDataString(maliciousPath)}"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _pathValidDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/path/api-validate?path={Uri.EscapeDataString(maliciousPath)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs new file mode 100644 index 00000000..c26abcbd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeErrorEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; + +/// +/// Contains security tests for the /{culture}/error route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeErrorEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeErrorEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeError_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/error"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs new file mode 100644 index 00000000..c5e19386 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeIndexEndpointTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; + +/// +/// Contains security tests for the /{culture} and / routes served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeIndexEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeIndexEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Home_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us"); + + // Assert + // the home page requires authentication, so an anonymous request must be redirected to the login page + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, System.StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Home_WhenCalledWithoutCulture_ShouldRedirectToDefaultCulture() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/"); + + // Assert + // the culture-less root must never demand authentication or leak internals, only redirect to the default culture + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/en-us/", response.Headers.Location!.ToString()); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Exception", content, System.StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs new file mode 100644 index 00000000..53c25060 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomeNotFoundViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; + +/// +/// Contains security tests for the /{culture}/not-found route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomeNotFoundViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomeNotFoundViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomeNotFoundView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/not-found"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs new file mode 100644 index 00000000..46954637 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Home/HomePrivacyEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Home; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Home; + +/// +/// Contains security tests for the /{culture}/privacy route served by the class. +/// +[ExcludeFromCodeCoverage] +public class HomePrivacyEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public HomePrivacyEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task HomePrivacy_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/privacy"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs new file mode 100644 index 00000000..2779c0fd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/item route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddLibraryView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage/item"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..15f4ce80 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibrariesScan; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-cancel-libraries-scan route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibrariesScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage cancelRequest = CreateCancelRequest(); + cancelRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage cancelRequest = CreateCancelRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the cancel libraries scan endpoint. + /// + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest() + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-cancel-libraries-scan") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..41ee3f42 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.CancelLibraryScan; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Contains security tests for the /{culture}/libraries/manage/{{libraryId}}/api-cancel-library-scan/{{scanId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CancelLibraryScanEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + cancelRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + [Fact] + public async Task CancelLibraryScan_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + HttpRequestMessage cancelRequest = CreateCancelRequest($"/en-us/libraries/manage/{libraryId}/api-cancel-library-scan/{scanId}"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(cancelRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans/{scanId}/cancel"); + } + + /// + /// Builds the cancel request that posts an empty JSON body to the given . + /// + /// The URL of the cancel endpoint. + /// The configured cancel request. + private static HttpRequestMessage CreateCancelRequest(string url) + { + HttpRequestMessage cancelRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + cancelRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + cancelRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return cancelRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs new file mode 100644 index 00000000..7222c593 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/EditLibrary/EditLibraryViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.EditLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.EditLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/item/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditLibraryViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditLibraryViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditLibraryView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/libraries/manage/item/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..5fbcb785 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetEnabledLibraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-enabled-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetEnabledLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetEnabledLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-enabled-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "libraries/enabled"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..e79104e2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-libraries"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "libraries"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..3092267b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetMetadataProviders/GetMetadataProvidersEndpointTests.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetMetadataProviders; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-metadata-providers/{{libraryId}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-metadata-providers/{libraryId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}/metadata-providers"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..06a1dc01 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetRunningLibraryScans; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-get-running-library-scans route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetRunningLibraryScansEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetRunningLibraryScans_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/libraries/manage/api-get-running-library-scans"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "libraries/scans/running"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs new file mode 100644 index 00000000..c176096d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/Index/LibrariesIndexViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.Index; + +/// +/// Contains security tests for the /{culture}/libraries/manage route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LibrariesIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LibrariesIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LibrariesIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/libraries/manage"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..c4f3a860 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ReorderMetadataProviders/ReorderMetadataProvidersEndpointTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderMetadataProviders; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ReorderMetadataProviders; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-reorder-metadata-providers route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderMetadataProvidersEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ReorderMetadataProvidersEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ReorderMetadataProviders_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); + } + + [Fact] + public async Task ReorderMetadataProviders_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/reorder"); + } + + /// + /// Builds the update request that reorders the metadata providers of the library identified by . + /// + /// The Id of the media library. + /// The configured update request. + private HttpRequestMessage CreateUpdateRequest(Guid libraryId) + { + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create( + libraryId: libraryId, + pluginIds: [Guid.NewGuid(), Guid.NewGuid()] + ); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-metadata-providers") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return updateRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..f2704f51 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-scan-libraries route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibrariesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage scanRequest = CreateScanRequest(); + scanRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + [Fact] + public async Task ScanLibraries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "libraries/scans"); + } + + /// + /// Builds the scan request that posts an empty JSON body to the scan libraries endpoint. + /// + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest() + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-scan-libraries") + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..5bbbfeb5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ScanLibrary; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-scan-library/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ScanLibraryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ScanLibrary_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + scanRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + [Fact] + public async Task ScanLibrary_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{libraryId}"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == $"libraries/{libraryId}/scans"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive injection + public async Task ScanLibrary_WithInjectionInId_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage scanRequest = CreateScanRequest($"/en-us/libraries/manage/api-scan-library/{Uri.EscapeDataString(maliciousId)}"); + scanRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(scanRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // note: the {id} route parameter is Guid-typed, so the malicious value fails model binding and never reaches + // the handler; the Web application reports the binding failure as a 200 response carrying success=false + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.StartsWith("libraries/", StringComparison.Ordinal)); + } + + /// + /// Builds the scan request that posts an empty JSON body to the given . + /// + /// The URL of the scan endpoint. + /// The configured scan request. + private static HttpRequestMessage CreateScanRequest(string url) + { + HttpRequestMessage scanRequest = new(HttpMethod.Post, url) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // the antiforgery middleware matches the content type exactly, so the charset suffix must be omitted + scanRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + scanRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return scanRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..a328ed61 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SetMetadataProviderEnabled/SetMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,93 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Plugins; +using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SetMetadataProviderEnabled; + +/// +/// Contains security tests for the /{culture}/libraries/manage/api-set-metadata-provider-enabled route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetMetadataProviderEnabledEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetMetadataProviderEnabledEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetMetadataProviderEnabled_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); + } + + [Fact] + public async Task SetMetadataProviderEnabled_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + HttpRequestMessage updateRequest = CreateUpdateRequest(libraryId, pluginId); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/metadata-providers/{pluginId}/enabled"); + } + + /// + /// Builds the update request that enables the metadata provider of the library identified by and . + /// + /// The Id of the media library. + /// The Id of the plugin providing the metadata. + /// The configured update request. + private HttpRequestMessage CreateUpdateRequest(Guid libraryId, Guid pluginId) + { + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create( + libraryId: libraryId, + pluginId: pluginId, + isEnabled: true + ); + HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-metadata-provider-enabled") + { + Content = JsonContent.Create(request) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return updateRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs new file mode 100644 index 00000000..333c37f5 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.EditBook; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/{{id}} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class EditBookViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public EditBookViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task EditBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books/{Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs new file mode 100644 index 00000000..762ab1e0 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books/api-get-library-items route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryItemsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PaginatedBookLiteDtoFixture _paginatedBookLiteDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetLibraryItemsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetLibraryItems_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("books/lite", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("'; DROP TABLE Books--")] // destructive SQL injection + [InlineData("' OR '1'='1")] // basic SQL injection + public async Task GetLibraryItems_WhenCalledWithInjectionInSearchTerm_ShouldRemainSecure(string maliciousSearchTerm) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + string expectedEndpoint = $"books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=False"; + _apiFactory.ApiClientStub.RegisterGetResponse(expectedEndpoint, _paginatedBookLiteDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/library/written-content-library/books-library/books/api-get-library-items?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}&shouldIgnoreThePrefixForAlphaPicker=false"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(expectedEndpoint, _apiFactory.ApiClientStub.GetEndpointsCalled); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs new file mode 100644 index 00000000..4784adfb --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; + +/// +/// Contains security tests for the /{culture}/library/written-content-library/books-library/books route served by the class. +/// +[ExcludeFromCodeCoverage] +public class BooksIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public BooksIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task BooksIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/en-us/library/written-content-library/books-library/books?libraryId={Guid.NewGuid()}"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("libraries/", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..e2e0c6d1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPluginSettings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; + +/// +/// Contains security tests for the /{culture}/admin/manage-plugins/api-get-plugin-settings/{pluginId} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPluginSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPluginSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + Guid pluginId = Guid.NewGuid(); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{pluginId}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == $"plugins/{pluginId}/settings"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Plugins--")] // destructive injection + public async Task GetPluginSettings_WithInjectionInPluginId_ShouldNotLeakOrError(string maliciousPluginId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/admin/manage-plugins/api-get-plugin-settings/{Uri.EscapeDataString(maliciousPluginId)}"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // note: the {pluginId} route parameter is Guid-typed, so the malicious value fails model binding and never + // reaches the handler; the Web application reports the binding failure as a 200 response carrying success=false + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("plugins/", StringComparison.Ordinal)); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs new file mode 100644 index 00000000..bd107f1b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/Index/PluginsIndexViewEndpointTests.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Plugins.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.Index; + +/// +/// Contains security tests for the /{culture}/admin/manage-plugins route served by the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsIndexViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PluginsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task PluginsIndex_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/admin/manage-plugins"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "plugins"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs new file mode 100644 index 00000000..c79c35ba --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Themes.ThemeAssets; + +/// +/// Contains security tests for the /theme-assets/{themeId}/{path} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAssetsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ThemeAssetsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ThemeAssets_WhenCalledWithoutAuthentication_ShouldServeAsset() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + byte[] expectedBytes = [0x89, 0x50, 0x4E, 0x47]; + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: expectedBytes, contentType: "image/png")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/theme-assets/test-theme/assets/logo.png"); + byte[] content = await response.Content.ReadAsByteArrayAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("image/png", response.Content.Headers.ContentType!.MediaType); + Assert.Equal(expectedBytes, content); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Themes--")] // destructive injection + public async Task ThemeAssets_WithInjectionInThemeId_ShouldNotLeakOrError(string maliciousThemeId) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x01], contentType: "application/octet-stream")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/theme-assets/{Uri.EscapeDataString(maliciousThemeId)}/assets/logo.png"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("..\\..\\appsettings.json")] // path traversal + public async Task ThemeAssets_WithInjectionInPath_ShouldNotLeakOrError(string maliciousPath) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterBlobResponse(_blobDataDtoFixture.Create(data: [0x01], contentType: "application/octet-stream")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync($"/theme-assets/test-theme/assets/{Uri.EscapeDataString(maliciousPath)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs new file mode 100644 index 00000000..00d4459d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Language.SetLanguage; + +/// +/// Contains security tests for the /{culture}/tools/language/set-language route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SetLanguageEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SetLanguageEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SetLanguage_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/language/set-language?newCulture=de-DE"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs new file mode 100644 index 00000000..7947bd26 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/AccessDenied/AccessDeniedViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.AccessDenied; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.AccessDenied; + +/// +/// Contains security tests for the /{culture}/auth/access-denied route served by the class. +/// +[ExcludeFromCodeCoverage] +public class AccessDeniedViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AccessDeniedViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AccessDeniedView_WhenCalledWithoutAuthentication_ShouldRenderAccessDeniedPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/access-denied"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs new file mode 100644 index 00000000..40e78d53 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains security tests for the /{culture}/auth/api-change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePassword_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(changePasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/change-password"); + } + + [Fact] + public async Task ChangePassword_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(changePasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/change-password"); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task ChangePassword_WithInjectionAttemptInNewPassword_ShouldRemainSecure(string maliciousNewPassword) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/change-password", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "OperationFailed"), HttpStatusCode.Forbidden, "auth/change-password")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(currentPassword: "OldPass123!", newPassword: maliciousNewPassword, newPasswordConfirm: maliciousNewPassword); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task ChangePassword_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/change-password", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "OperationFailed"), + HttpStatusCode.Conflict)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + ChangePasswordRequest request = _changePasswordRequestFixture.Create(); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateChangePasswordRequest(request, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the change password request that sends the given to the change password endpoint. + /// + /// The change password request to send. + /// The antiforgery token to include in the request. + /// The configured change password request. + private static HttpRequestMessage CreateChangePasswordRequest(ChangePasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage changePasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-change-password") + { + Content = JsonContent.Create(request) + }; + changePasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + changePasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + changePasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return changePasswordRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs new file mode 100644 index 00000000..23bd174c --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.ChangePassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.ChangePassword; + +/// +/// Contains security tests for the /{culture}/auth/change-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public ChangePasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task ChangePasswordView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/change-password"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs new file mode 100644 index 00000000..300c5e01 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; + +/// +/// Contains security tests for the /{culture}/auth/login/{returnUrl?} route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LoginViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LoginViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task LoginView_WhenCalledWithoutAuthentication_ShouldRenderLoginPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/login"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("login-form", content); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs new file mode 100644 index 00000000..7e0374f8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Logout/LogoutEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Logout; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Logout; + +/// +/// Contains security tests for the /{culture}/auth/logout route served by the class. +/// +[ExcludeFromCodeCoverage] +public class LogoutEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public LogoutEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task Logout_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/logout"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs new file mode 100644 index 00000000..4a26f5b3 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains security tests for the /{culture}/auth/api-recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task RecoverPassword_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/recover-password", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RecoveryFailed"), HttpStatusCode.Forbidden, "auth/recover-password")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: maliciousUsername, totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task RecoverPassword_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + // Act + HttpResponseMessage response = await client.SendAsync(recoverPasswordRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/recover-password"); + } + + [Fact] + public async Task RecoverPassword_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/recover-password", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RecoveryFailed"), + HttpStatusCode.Conflict)); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(username: "testuser", totpCode: "123456"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRecoverPasswordRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the recover password request that sends the given to the recover password endpoint. + /// + /// The recover password request to send. + /// The antiforgery token to include in the request. + /// The configured recover password request. + private static HttpRequestMessage CreateRecoverPasswordRequest(RecoverPasswordRequest request, string antiforgeryToken) + { + HttpRequestMessage recoverPasswordRequest = new(HttpMethod.Post, "/en-us/auth/api-recover-password") + { + Content = JsonContent.Create(request) + }; + recoverPasswordRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + recoverPasswordRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + recoverPasswordRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return recoverPasswordRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs new file mode 100644 index 00000000..8f2cbdd7 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; + +/// +/// Contains security tests for the /{culture}/auth/recover-password route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RecoverPasswordViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RecoverPasswordView_WhenCalledWithoutAuthentication_ShouldRenderRecoverPasswordPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/recover-password"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs new file mode 100644 index 00000000..85a1546a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains security tests for the /{culture}/auth/api-register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly RegisterRequestFixture _registerRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("admin'--")] // comment injection + [InlineData("' UNION SELECT * FROM Users--")] // union injection + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("{{7*7}}")] // template injection + public async Task Register_WithInjectionAttemptInUsername_ShouldRemainSecure(string maliciousUsername) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/register", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RegistrationFailed"), HttpStatusCode.Forbidden, "auth/register")); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: maliciousUsername, password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.DoesNotContain("SQL", content); + Assert.DoesNotContain("Exception", 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); + } + + [Fact] + public async Task Register_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + // Act + HttpResponseMessage response = await client.SendAsync(registerRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == "auth/register"); + } + + [Fact] + public async Task Register_WhenApiReturnsError_ShouldReturnCleanError() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException("auth/register", new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "RegistrationFailed"), + HttpStatusCode.Conflict)); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + RegisterRequest request = _registerRequestFixture.Create(username: "newuser", password: "Abcd123$", passwordConfirm: "Abcd123$"); + + // Act + HttpResponseMessage response = await client.SendAsync(CreateRegisterRequest(request, antiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Builds the register request that sends the given to the register endpoint. + /// + /// The register request to send. + /// The antiforgery token to include in the request. + /// The configured register request. + private static HttpRequestMessage CreateRegisterRequest(RegisterRequest request, string antiforgeryToken) + { + HttpRequestMessage registerRequest = new(HttpMethod.Post, "/en-us/auth/api-register") + { + Content = JsonContent.Create(request) + }; + registerRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + registerRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + registerRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return registerRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs new file mode 100644 index 00000000..6f18a19f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterViewEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Register; + +/// +/// Contains security tests for the /{culture}/auth/register route served by the class. +/// +[ExcludeFromCodeCoverage] +public class RegisterViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RegisterViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RegisterView_WhenCalledWithoutAuthentication_ShouldRenderRegisterPage() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/auth/register"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + } +} From f42dc709ded6ff8126c533894c8108b22459322d Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:20:08 -0700 Subject: [PATCH 6/7] Standardizes test conventions and documentation --- .../RolePermissionEntityFixture.cs | 35 ++- .../UserAuthorizationEntityFixture.cs | 14 +- .../Authorization/UserRoleEntityFixture.cs | 62 +++-- .../BookLibrary/BookEntityFixture.cs | 12 +- .../UsersManagement/UserEntityFixture.cs | 30 ++- .../Queries/GetBooks/GetBooksQueryFixture.cs | 8 +- .../GetBooksLite/GetBooksLiteQueryFixture.cs | 14 +- .../BookLibrary/BookMetadataDtoFixture.cs | 99 +++++--- .../Books/AddBookRequestFixture.cs | 188 +++++++++----- .../Books/GetBooksLiteRequestFixture.cs | 6 +- .../Thumbnails/ThumbnailResponseFixture.cs | 7 +- .../BookLibrary/Books/BookResponseFixture.cs | 6 +- .../BookLibraryAggregate/BookFixture.cs | 2 +- .../ThemeEngineOptionsDtoFixture.cs | 17 +- .../Common/Api/StubApiHttpClient.cs | 14 +- .../DTO/Authorization/RoleDtoFixture.cs | 5 +- .../Common/DTO/Themes/ThemeInfoDtoFixture.cs | 20 +- .../DTO/Themes/ThemeNavMenuDtoFixture.cs | 50 +--- .../Common/DTO/Themes/ThemePageDtoFixture.cs | 10 +- .../Themes/ThemeRenderDocumentDtoFixture.cs | 8 +- .../DTO/Themes/ThemeResponseDtoFixture.cs | 21 +- .../Themes/ThemeSettingsResponseDtoFixture.cs | 7 +- .../Themes/ThemeTemplateResponseDtoFixture.cs | 5 +- .../Common/Models/SectionModelFixture.cs | 9 +- .../Authorization/AddRoleRequestFixture.cs | 9 +- .../Libraries/GetBooksLiteRequestFixture.cs | 7 +- .../Authentication/LoginViewRequestFixture.cs | 8 +- .../ChangePasswordRequestFixture.cs | 15 +- .../UsersManagement/LoginRequestFixture.cs | 13 +- .../RecoverPasswordRequestFixture.cs | 9 +- .../UsersManagement/RegisterRequestFixture.cs | 14 +- .../Setup/AuthenticatedLuminaApiFactory.cs | 28 +-- .../Roles/DeleteRoleEndpointTests.cs | 10 +- .../Roles/UpdateRoleEndpointTests.cs | 44 ++-- .../GetDirectoriesEndpointTests.cs | 11 +- .../Files/GetFilesEndpointTests.cs | 16 +- .../Files/GetTreeFilesEndpointTests.cs | 16 +- .../AddLibrary/AddLibraryEndpointTests.cs | 42 ++-- .../DeleteLibraryEndpointTests.cs | 29 +-- .../GetEnabledLibrariesEndpointTests.cs | 16 +- .../GetLibraries/GetLibrariesEndpointTests.cs | 30 +-- .../GetLibrary/GetLibraryEndpointTests.cs | 15 +- .../GetLibraryScanProgressEndpointTests.cs | 15 +- .../ScanLibrariesEndpointTests.cs | 17 +- .../ScanLibrary/ScanLibraryEndpointTests.cs | 17 +- .../UpdateLibraryEndpointTests.cs | 64 +++-- .../Books/GetBooks/GetBooksEndpointTests.cs | 108 ++++---- .../GetBooksLite/GetBooksLiteEndpointTests.cs | 101 +++----- .../CheckInitializationEndpointTests.cs | 15 +- .../SetupApplicationEndpointTests.cs | 48 ++-- .../GetPlugins/GetPluginsEndpointTests.cs | 32 +-- .../ChangePasswordEndpointTests.cs | 52 ++-- .../Authentication/LoginEndpointTests.cs | 121 ++++----- .../RecoverPasswordEndpointTests.cs | 52 ++-- .../Authentication/RegisterEndpointTests.cs | 61 +++-- .../GetAuthorizationEndpointTests.cs | 56 ++--- .../GetUserPermissionsEndpointTests.cs | 12 +- ...dateUserRoleAndPermissionsEndpointTests.cs | 75 +++--- .../Roles/GetRoles/GetRolesEndpointTests.cs | 11 +- .../GetLibraries/GetLibrariesEndpointTests.cs | 6 +- .../SaveLibrary/SaveLibraryEndpointTests.cs | 9 +- .../Login/LoginEndpointTests.cs | 35 ++- .../Common/Setup/LuminaApiFactory.cs | 87 ++----- .../Roles/AddRoleEndpointTests.cs | 20 +- .../Roles/UpdateRoleEndpointTests.cs | 47 ++-- .../AddLibrary/AddLibraryEndpointTests.cs | 46 ++-- .../CancelLibrariesScanEndpointTests.cs | 25 +- .../CancelLibraryScanEndpointTests.cs | 20 +- .../DeleteLibraryEndpointTests.cs | 21 +- .../GetEnabledLibrariesEndpointTests.cs | 25 +- .../GetLibraries/GetLibrariesEndpointTests.cs | 25 +- .../GetLibrary/GetLibraryEndpointTests.cs | 41 +-- .../GetLibraryScanProgressEndpointTests.cs | 20 +- .../GetRunningLibraryScansEndpointTests.cs | 25 +- .../ScanLibrariesEndpointTests.cs | 25 +- .../ScanLibrary/ScanLibraryEndpointTests.cs | 20 +- .../UpdateLibraryEndpointTests.cs | 68 +++-- .../ChangePasswordEndpointTests.cs | 56 +++-- .../Authentication/LoginEndpointTests.cs | 73 +++--- .../Authentication/RegisterEndpointTests.cs | 60 +++-- ...mina.Presentation.Api.SecurityTests.csproj | 3 + .../Roles/GetRoles/GetRolesEndpointTests.cs | 16 +- .../DeleteLibraryEndpointTests.cs | 8 +- .../SaveLibrary/SaveLibraryEndpointTests.cs | 19 +- .../GetPlugins/GetPluginsEndpointTests.cs | 8 +- .../InstallPluginEndpointTests.cs | 8 +- .../UpdatePluginSettingsEndpointTests.cs | 8 +- .../Login/LoginEndpointTests.cs | 22 +- .../PermissionEntityMappingTests.cs | 27 +- .../Authorization/RoleEntityMappingTests.cs | 67 ++--- .../UserAuthorizationEntityMappingTests.cs | 42 ++-- .../Common/Metadata/GenreDtoMappingTests.cs | 25 +- .../Metadata/GenreEntityMappingTests.cs | 29 ++- .../Common/Metadata/TagDtoMappingTests.cs | 25 +- .../Common/Metadata/TagEntityMappingTests.cs | 29 ++- .../Books/AddBookRequestMappingTests.cs | 86 ++----- .../Books/BookEntityMappingTests.cs | 52 ++-- .../Books/BookMetadataDtoMappingTests.cs | 5 +- .../Common/IsbnEntityMappingTests.cs | 21 +- .../UserManagement/Users/UserMappingTests.cs | 76 +----- .../GetPermissionsQueryHandlerTests.cs | 20 +- .../AddRole/AddRoleCommandHandlerTests.cs | 27 +- .../DeleteRoleCommandHandlerTests.cs | 8 +- .../UpdateRoleCommandHandlerTests.cs | 27 +- .../GetRolePermissionsQueryHandlerTests.cs | 31 +-- .../GetRoles/GetRolesQueryHandlerTests.cs | 6 +- .../GetPathParentQueryHandlerTests.cs | 6 +- .../CheckInitializationQueryHandlerTests.cs | 8 +- .../CancelLibrariesScanCommandHandlerTests.cs | 16 +- .../ScanLibrariesCommandHandlerTests.cs | 19 +- .../LibraryDeletedDomainEventHandlerTests.cs | 11 +- .../LibrarySavedDomainEventHandlerTests.cs | 11 +- ...ibraryScanQueuedDomainEventHandlerTests.cs | 14 +- .../GetEnabledLibrariesQueryHandlerTests.cs | 11 +- .../GetLibrariesQueryHandlerTests.cs | 11 +- .../GetLibrary/GetLibraryQueryHandlerTests.cs | 15 +- ...GetRunningLibraryScansQueryHandlerTests.cs | 12 +- .../AddBook/AddBookCommandHandlerTests.cs | 33 +-- .../AddBook/AddBookCommandValidatorTests.cs | 14 ++ .../GetBooks/GetBooksQueryHandlerTests.cs | 50 +--- .../GetBooksLiteQueryHandlerTests.cs | 50 +--- .../GetPlugins/GetPluginsQueryHandlerTests.cs | 12 +- .../GetThemeArchiveQueryHandlerTests.cs | 7 +- .../GetThemeAssetQueryHandlerTests.cs | 9 +- ...erRoleAndPermissionsCommandHandlerTests.cs | 118 ++++----- .../GetUserPermissionsQueryHandlerTests.cs | 32 ++- .../GetUserRoleQueryHandlerTests.cs | 28 +-- .../BookLibrary/Books/AddBookRequestTests.cs | 3 +- .../Books/GetBooksLiteRequestTests.cs | 4 +- .../Authorization/RoleRepositoryTests.cs | 126 ++-------- ...DirectoryScanFingerprintRepositoryTests.cs | 8 +- .../Libraries/LibraryRepositoryTests.cs | 18 +- .../Libraries/LibraryScanRepositoryTests.cs | 16 +- ...ibraryScanStagingResultsRepositoryTests.cs | 6 +- .../Repositories/Users/UserRepositoryTests.cs | 236 +++++------------- .../Users/UserSettingsRepositoryTests.cs | 6 +- .../Core/Seed/DataSeedServiceTests.cs | 31 +-- .../MediaLibraryScanningServiceTests.cs | 27 +- .../Scanners/BookLibraryTypeScannerTests.cs | 41 +-- .../Plugins/PluginDetectionSyncJobTests.cs | 35 +-- .../Core/Plugins/PluginInstallerTests.cs | 5 +- .../Core/Plugins/PluginSettingsStoreTests.cs | 28 +-- .../Roles/AddRole/AddRoleEndpointTests.cs | 27 +- .../DeleteRole/DeleteRoleEndpointTests.cs | 10 +- .../GetRolePermissionsEndpointTests.cs | 34 +-- .../Roles/GetRoles/GetRolesEndpointTests.cs | 8 +- .../UpdateRole/UpdateRoleEndpointTests.cs | 34 +-- .../FileSystem/GetTypeEndpointTests.cs | 12 +- .../Path/CheckPathExistsEndpointTests.cs | 8 +- .../Path/ValidatePathEndpointTests.cs | 8 +- .../AddLibrary/AddLibraryEndpointTests.cs | 3 +- .../ScanLibrariesEndpointTests.cs | 6 +- .../ScanLibrary/ScanLibraryEndpointTests.cs | 8 +- .../UpdateLibraryEndpointTests.cs | 3 +- .../Books/GetBook/GetBookEndpointTests.cs | 4 +- .../Books/GetBooks/GetBooksEndpointTests.cs | 17 +- .../GetBooksLite/GetBooksLiteEndpointTests.cs | 27 +- .../CheckInitializationEndpointTests.cs | 8 +- .../SetupApplicationEndpointTests.cs | 8 +- .../ChangePasswordEndpointTests.cs | 8 +- .../GetUsers/GetUsersEndpointTests.cs | 4 +- .../Login/LoginEndpointTests.cs | 8 +- .../RecoverPasswordEndpointTests.cs | 8 +- .../Register/RegisterEndpointTests.cs | 8 +- .../GetAuthorizationEndpointTests.cs | 14 +- .../GetUserPermissionsEndpointTests.cs | 16 +- .../GetUserRole/GetUserRoleEndpointTests.cs | 18 +- ...dateUserRoleAndPermissionsEndpointTests.cs | 45 ++-- .../Common/Api/ApiHttpClientTests.cs | 27 +- .../AuthorizationServiceTests.cs | 12 +- .../Security/CryptographyServiceTests.cs | 18 +- .../EncryptionSettingsModelValidatorTests.cs | 8 +- .../ServerConfigurationModelValidatorTests.cs | 10 +- .../Roles/AddRole/AddRoleEndpointTests.cs | 6 +- .../DeleteTheme/DeleteThemeEndpointTests.cs | 12 +- .../DownloadThemeEndpointTests.cs | 17 +- .../RestoreTheme/RestoreThemeEndpointTests.cs | 10 +- .../SetCurrentThemeEndpointTests.cs | 8 +- .../GetDirectoriesEndpointTests.cs | 4 +- .../ValidatePath/ValidatePathEndpointTests.cs | 6 +- .../GetLibraryItemsEndpointTests.cs | 27 +- .../Index/BooksIndexViewEndpointTests.cs | 14 +- .../ThemeAssets/ThemeAssetsEndpointTests.cs | 13 +- .../SetLanguage/SetLanguageEndpointTests.cs | 9 +- .../Login/LoginViewEndpointTests.cs | 12 +- .../RecoverPasswordEndpointTests.cs | 4 +- .../Register/RegisterEndpointTests.cs | 6 +- .../Core/Themes/ThemeLayoutRendererTests.cs | 39 ++- .../Core/Themes/ThemePageRendererTests.cs | 8 +- .../Core/Themes/ThemeServiceTests.cs | 6 +- 190 files changed, 2180 insertions(+), 2814 deletions(-) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs index 3270b06f..7029f0fd 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/RolePermissionEntityFixture.cs @@ -2,6 +2,7 @@ using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -20,23 +21,33 @@ public class RolePermissionEntityFixture /// /// Creates a random valid . /// + /// Optional. The Id of the role permission association. + /// Optional. The Id of the role the permission is granted to. + /// Optional. The role the permission is granted to. + /// Optional. The Id of the permission granted to the role. + /// Optional. The permission granted to the role. /// The created . - public RolePermissionEntity Create() + public RolePermissionEntity Create( + Guid? id = null, + Guid? roleId = null, + RoleEntity? role = null, + Guid? permissionId = null, + PermissionEntity? permission = null) { - PermissionEntity permission = new() + RoleEntity resolvedRole = role ?? new RoleEntity { - Id = _faker.Random.Guid(), - PermissionName = _faker.PickRandom(), + Id = roleId ?? _faker.Random.Guid(), + RoleName = _faker.Random.String2(10), CreatedOnUtc = _faker.Date.Past(), CreatedBy = _faker.Random.Guid(), UpdatedOnUtc = _faker.Date.Recent(), UpdatedBy = _faker.Random.Guid() }; - RoleEntity role = new() + PermissionEntity resolvedPermission = permission ?? new PermissionEntity { - Id = _faker.Random.Guid(), - RoleName = _faker.Random.String2(10), + Id = permissionId ?? _faker.Random.Guid(), + PermissionName = _faker.PickRandom(), CreatedOnUtc = _faker.Date.Past(), CreatedBy = _faker.Random.Guid(), UpdatedOnUtc = _faker.Date.Recent(), @@ -46,11 +57,11 @@ public class RolePermissionEntityFixture return new Faker() .CustomInstantiator(f => new RolePermissionEntity { - Id = f.Random.Guid(), - RoleId = role.Id, - Role = role, - PermissionId = permission.Id, - Permission = permission, + Id = id ?? f.Random.Guid(), + RoleId = resolvedRole.Id, + Role = role ?? resolvedRole, + PermissionId = resolvedPermission.Id, + Permission = permission ?? resolvedPermission, CreatedOnUtc = f.Date.Past(), CreatedBy = f.Random.Guid(), UpdatedOnUtc = f.Date.Recent(), diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs index 4e1bada0..57514f07 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserAuthorizationEntityFixture.cs @@ -20,16 +20,22 @@ public class UserAuthorizationEntityFixture /// /// Optional. The user Id to use. If null, a random GUID will be generated. /// Whether the user should have admin role. + /// Optional. The role associated to the user. If null, it is derived from the flag. + /// Optional. The permissions associated to the user. If null, a default set is generated. /// The created entity. - public UserAuthorizationEntity Create(Guid? userId = null, bool isAdmin = false) + public UserAuthorizationEntity Create( + Guid? userId = null, + bool isAdmin = false, + string? role = null, + IReadOnlySet? permissions = null) { - string role = isAdmin ? "Admin" : string.Empty; + string resolvedRole = role ?? (isAdmin ? "Admin" : string.Empty); return new UserAuthorizationEntity { UserId = userId ?? Guid.NewGuid(), - Role = role, - Permissions = new HashSet + Role = resolvedRole, + Permissions = permissions ?? new HashSet { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanRegisterUsers diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs index e7142a7d..acce952c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Authorization/UserRoleEntityFixture.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -14,36 +16,52 @@ namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; [ExcludeFromCodeCoverage] public class UserRoleEntityFixture { + private readonly Faker _faker = new(); + /// /// Creates a random valid . /// + /// Optional. The Id of the user role association. + /// Optional. The Id of the user the role is granted to. + /// Optional. The user the role is granted to. + /// Optional. The Id of the role granted to the user. + /// Optional. The role granted to the user. /// The created . - public UserRoleEntity Create() + public UserRoleEntity Create( + Guid? id = null, + Guid? userId = null, + UserEntity? user = null, + Guid? roleId = null, + RoleEntity? role = null) { + UserEntity resolvedUser = user ?? new UserEntity + { + Id = userId ?? _faker.Random.Guid(), + Username = _faker.Internet.UserName(), + Password = _faker.Internet.Password(), + Libraries = [], + UserRole = null, + UserPermissions = [], + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = _faker.Random.Guid() + }; + + RoleEntity resolvedRole = role ?? new RoleEntity + { + Id = roleId ?? _faker.Random.Guid(), + RoleName = _faker.Random.String2(_faker.Random.Number(1, 50)), + CreatedOnUtc = _faker.Date.Past(), + CreatedBy = _faker.Random.Guid() + }; + return new Faker() .CustomInstantiator(f => new UserRoleEntity { - Id = f.Random.Guid(), - UserId = f.Random.Guid(), - User = new() - { - Id = f.Random.Guid(), - Username = f.Internet.UserName(), - Password = f.Internet.Password(), - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedOnUtc = f.Date.Past(), - CreatedBy = f.Random.Guid() - }, - RoleId = f.Random.Guid(), - Role = new() - { - Id = f.Random.Guid(), - RoleName = f.Random.String2(f.Random.Number(1, 50)), - CreatedOnUtc = f.Date.Past(), - CreatedBy = f.Random.Guid() - }, + Id = id ?? f.Random.Guid(), + UserId = resolvedUser.Id, + User = user ?? resolvedUser, + RoleId = resolvedRole.Id, + Role = role ?? resolvedRole, CreatedOnUtc = f.Date.Past(), CreatedBy = f.Random.Guid() }) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs index 19c76868..fe191177 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntityFixture.cs @@ -28,13 +28,15 @@ public class BookEntityFixture /// Optional. The file system path of the book. /// Optional. The title of the book. /// Optional. The original title of the book. + /// Whether the book should include its owned metadata collections (Tags, Genres, ISBNs, Ratings) or not. /// The created . public BookEntity Create( Guid? id = null, Guid? libraryId = null, string? path = null, string? title = null, - string? originalTitle = null) + string? originalTitle = null, + bool includeMetadata = true) { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); @@ -58,8 +60,8 @@ public class BookEntityFixture .RuleFor(x => x.OriginalLanguageCode, f => f.Random.String2(2)) .RuleFor(x => x.OriginalLanguageName, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.OriginalLanguageNativeName, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.Tags, f => [.. CreateTags(f.Random.Number(1, 5))]) - .RuleFor(x => x.Genres, f => [.. CreateGenres(f.Random.Number(1, 5))]) + .RuleFor(x => x.Tags, f => includeMetadata ? [.. CreateTags(f.Random.Number(1, 5))] : []) + .RuleFor(x => x.Genres, f => includeMetadata ? [.. CreateGenres(f.Random.Number(1, 5))] : []) .RuleFor(x => x.Publisher, f => f.Random.String2(f.Random.Number(1, 100))) .RuleFor(x => x.PageCount, _random.Next(100, 300)) .RuleFor(x => x.Format, f => f.PickRandom()) @@ -74,8 +76,8 @@ public class BookEntityFixture .RuleFor(x => x.GoogleBooksId, CreateGoogleBooksId) .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(x => x.ISBNs, f => CreateIsbns(f.Random.Number(1, 5))) - .RuleFor(x => x.Ratings, f => CreateBookRatings(f.Random.Number(1, 5))) + .RuleFor(x => x.ISBNs, f => includeMetadata ? CreateIsbns(f.Random.Number(1, 5)) : []) + .RuleFor(x => x.Ratings, f => includeMetadata ? CreateBookRatings(f.Random.Number(1, 5)) : []) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.UpdatedOnUtc, f => f.Date.Recent()) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs index 8fbb2def..ee757fb6 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserEntityFixture.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -23,13 +24,28 @@ public class UserEntityFixture /// Number of libraries to generate. Default is 0. /// Optional username to pin, or to generate a random one. /// Optional password to pin, or to generate a random one. + /// Optional Id to pin, or to generate a random one. + /// Optional user role association to pin when including it. + /// Optional user permission associations to pin when including them. + /// Whether the user should include a user role association or not. + /// Whether the user should include user permission associations or not. + /// Optional collection of libraries to pin for the user, or to generate them based on . /// The created user entity. - public UserEntity Create(int libraryCount = 0, string? username = null, string? password = null) + public UserEntity Create( + int libraryCount = 0, + string? username = null, + string? password = null, + Guid? id = null, + UserRoleEntity? userRole = null, + IEnumerable? userPermissions = null, + bool includeUserRole = false, + bool includeUserPermissions = false, + ICollection? libraries = null) { - Guid userId = Guid.NewGuid(); - List libraries = libraryCount > 0 + Guid userId = id ?? Guid.NewGuid(); + ICollection resolvedLibraries = libraries ?? (libraryCount > 0 ? CreateLibraries(libraryCount, userId) - : []; + : []); return new Faker() .CustomInstantiator(f => new UserEntity @@ -39,9 +55,9 @@ public class UserEntityFixture Password = default!, CreatedOnUtc = default, TotpSecret = default, - Libraries = libraries, - UserPermissions = [], - UserRole = null, + Libraries = resolvedLibraries, + UserPermissions = includeUserPermissions ? (userPermissions ?? []).ToList() : [], + UserRole = includeUserRole ? userRole : null, CreatedBy = userId }) .RuleFor(x => x.Username, f => username ?? f.Internet.UserName()) diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs index caa8d830..9cfd04eb 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryFixture.cs @@ -28,20 +28,22 @@ public class GetBooksQueryFixture /// Optional. The search term used to filter results. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the query should include pagination data or not. /// The created query to get books. public GetBooksQuery Create( Guid? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? sortBy = null, - SortOrder? sortOrder = null) + SortOrder? sortOrder = null, + bool includePaginationData = true) { return new GetBooksQuery( - paginationData ?? new PaginationDataDto + includePaginationData ? paginationData ?? new PaginationDataDto { CurrentPage = _faker.Random.Number(1, 100), PerPage = _faker.Random.Number(1, 200) - }, + } : null, new LibraryFilterDto { LibraryId = libraryId ?? _faker.Random.Guid(), diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs index c7a7d0d9..a93511b1 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryFixture.cs @@ -27,31 +27,33 @@ public class GetBooksLiteQueryFixture /// Optional. The pagination data of the query. /// Optional. The search term used to filter results. /// Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker. - /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. + /// Whether the query should include pagination data or not. /// The created query to get the lightweight details of books. public GetBooksLiteQuery Create( Guid? libraryId = null, PaginationDataDto? paginationData = null, string? searchTerm = null, string? filterAlphaKey = null, - bool ignoreThePrefixForAlphaPicker = false, + bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, - SortOrder? sortOrder = null) + SortOrder? sortOrder = null, + bool includePaginationData = true) { return new GetBooksLiteQuery( - paginationData ?? new PaginationDataDto + includePaginationData ? paginationData ?? new PaginationDataDto { CurrentPage = _faker.Random.Number(1, 100), PerPage = _faker.Random.Number(1, 200) - }, + } : null, new LibraryFilterDto { LibraryId = libraryId ?? _faker.Random.Guid(), SearchTerm = searchTerm, FilterAlphaKey = filterAlphaKey, - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker }, sortBy, sortOrder ?? _faker.PickRandom() diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs index 7fa9d6e3..498147dc 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -25,53 +26,93 @@ public class BookMetadataDtoFixture /// Optional. The title of the book. /// Optional. The original title of the book. /// Optional. A brief description or summary of the book. - /// Optional. The Goodreads ID of the book. - /// Optional. The format of the book. + /// Optional. The release information of the book. + /// Optional. The genres of the book. + /// Optional. The tags of the book. + /// Optional. The language of the book. + /// Optional. The original language of the book. /// Optional. The name of the publisher of the book. /// Optional. The number of pages in the book. - /// Whether optional properties should be included. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads ID of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library ID of the book. + /// Optional. The LibraryThing ID of the book. + /// Optional. The Google Books ID of the book. + /// Optional. The Barnes and Noble ID of the book. + /// Optional. The Apple Books ID of the book. + /// Optional. The ISBNs of the book. + /// Optional. The contributors of the book. + /// Optional. The ratings of the book. + /// Optional. The path of the cover image of the book. + /// Whether the title should be included, or forced to . + /// Whether the properties that are not explicitly provided should be randomized, or left . /// The created . public BookMetadataDto Create( string? title = null, string? originalTitle = null, string? description = null, - string? goodreadsId = null, - BookFormat? format = null, + ReleaseInfoDto? releaseInfo = null, + List? genres = null, + List? tags = null, + LanguageInfoDto? language = null, + LanguageInfoDto? originalLanguage = null, string? publisher = null, int? pageCount = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeriesDto? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null, + string? coverImagePath = null, + bool includeTitle = true, bool includeOptionalProperties = true) { int releaseYear = _faker.Random.Int(1900, 2024); return new BookMetadataDto( - title ?? _faker.Lorem.Sentence(3), + includeTitle ? title ?? (includeOptionalProperties ? _faker.Lorem.Sentence(3) : null) : null, originalTitle, description, - includeOptionalProperties - ? new ReleaseInfoDto(new DateOnly(releaseYear, 1, 1), releaseYear, null, null, _faker.Address.CountryCode(), null) - : null, - includeOptionalProperties ? [new GenreDto(_faker.Lorem.Word())] : null, - includeOptionalProperties ? [new TagDto(_faker.Lorem.Word())] : null, - includeOptionalProperties ? new LanguageInfoDto("en", "English", "English") : null, - null, + releaseInfo ?? (includeOptionalProperties ? new ReleaseInfoDto(new DateOnly(releaseYear, 1, 1), releaseYear, null, null, _faker.Address.CountryCode(), null) : null), + genres ?? (includeOptionalProperties ? [new GenreDto(_faker.Lorem.Word())] : null), + tags ?? (includeOptionalProperties ? [new TagDto(_faker.Lorem.Word())] : null), + language ?? (includeOptionalProperties ? new LanguageInfoDto("en", "English", "English") : null), + originalLanguage, publisher, pageCount, - format ?? _faker.PickRandom(), - null, - includeOptionalProperties ? _faker.Random.Int(1, 10) : null, - null, - null, + format ?? (includeOptionalProperties ? _faker.PickRandom() : null), + edition, + volumeNumber ?? (includeOptionalProperties ? _faker.Random.Int(1, 10) : null), + series, + asin, goodreadsId, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null); + lccn, + oclcNumber, + openLibraryId, + libraryThingId, + googleBooksId, + barnesAndNobleId, + appleBooksId, + isbns, + contributors, + ratings, + coverImagePath); } /// diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs index c8f5ad7d..0217fa67 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestFixture.cs @@ -9,6 +9,7 @@ using Lumina.Contracts.Fixtures.Common.Setup; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; #endregion @@ -37,8 +38,48 @@ public class AddBookRequestFixture /// /// Creates a random valid request to add a book. /// + /// Optional. The Id of the media library the book belongs to. + /// Optional. The file system path of the book. + /// Optional. The written content metadata of the book. + /// Optional. The format of the book. + /// Optional. The edition of the book. + /// Optional. The volume or book number in the series. + /// Optional. The series the book is part of. + /// Optional. The ASIN of the book. + /// Optional. The Goodreads Id of the book. + /// Optional. The LCCN of the book. + /// Optional. The OCLC number of the book. + /// Optional. The Open Library Id of the book. + /// Optional. The LibraryThing Id of the book. + /// Optional. The Google Books Id of the book. + /// Optional. The Barnes and Noble Id of the book. + /// Optional. The Apple Books Id of the book. + /// Optional. The ISBNs of the book. + /// Optional. The contributors of the book. + /// Optional. The ratings of the book. + /// Whether the properties that are not explicitly provided should be randomized, or left . /// The created request to add a book. - public AddBookRequest Create() + public AddBookRequest Create( + Guid? libraryId = null, + string? path = null, + WrittenContentMetadataDto? metadata = null, + BookFormat? format = null, + string? edition = null, + float? volumeNumber = null, + BookSeriesDto? series = null, + string? asin = null, + string? goodreadsId = null, + string? lccn = null, + string? oclcNumber = null, + string? openLibraryId = null, + string? libraryThingId = null, + string? googleBooksId = null, + string? barnesAndNobleId = null, + string? appleBooksId = null, + List? isbns = null, + List? contributors = null, + List? ratings = null, + bool includeOptionalProperties = true) { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); @@ -128,7 +169,7 @@ public class AddBookRequestFixture .RuleFor(e => e.LanguageCode, f => f.Random.String2(2)) .RuleFor(e => e.NativeName, f => f.Random.String2(f.Random.Number(1, 50))); - Faker metadata = new Faker() + Faker metadataFaker = new Faker() .CustomInstantiator(f => new WrittenContentMetadataDto( default!, default, @@ -210,62 +251,91 @@ public class AddBookRequestFixture default!, default! )) - .RuleFor(x => x.LibraryId, _fixture.Create()) - .RuleFor(x => x.Path, f => f.System.FilePath()) - .RuleFor(x => x.Metadata, metadata) - .RuleFor(x => x.Format, _fixture.Create()) - .RuleFor(x => x.Edition, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.VolumeNumber, _random.Next(1, 3)) - .RuleFor(x => x.ASIN, f => f.Random.String2(10)) - .RuleFor(x => x.GoodreadsId, _random.Next(100000, 500000).ToString()) - .RuleFor(x => x.LCCN, f => - { - string letters = new([.. Enumerable.Range(0, f.Random.Number(0, 3)).Select(_ => f.Random.Char('a', 'z'))]); - string digits = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - return letters + digits; - }) - .RuleFor(x => x.OCLCNumber, f => - { - string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; - string prefix = f.Random.ArrayElement(prefixes); - string number; - switch (prefix) - { - case "ocm": - number = f.Random.String2(8, "0123456789"); - break; - case "ocn": - number = f.Random.String2(f.Random.Number(9, 11), "0123456789"); - break; - case "on": - number = f.Random.String2(10, "0123456789"); - break; - case "(OCoLC)": - number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - break; - default: - number = f.Random.String2(f.Random.Number(8, 10), "0123456789"); - return number; - } - return prefix + number; - }) - .RuleFor(x => x.OpenLibraryId, f => - { - int firstDigit = f.Random.Number(1, 9); - string remainingDigits = f.Random.String2(f.Random.Number(0, 6), "0123456789"); - char suffix = f.Random.ArrayElement(['A', 'M', 'W']); - return $"OL{firstDigit}{remainingDigits}{suffix}"; - }) - .RuleFor(x => x.LibraryThingId, f => f.Random.String2(f.Random.Number(1, 50))) - .RuleFor(x => x.GoogleBooksId, f => - { - const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[f.Random.Number(VALID_CHARS.Length - 1)])]); - }) - .RuleFor(x => x.BarnesAndNobleId, f => f.Random.String2(10, "0123456789")) - .RuleFor(x => x.AppleBooksId, f => $"id{f.Random.Number(1, 999999)}") - .RuleFor(p => p.ISBNs, f => isbn.Generate(f.Random.Number(1, 5))) - .RuleFor(p => p.Ratings, f => rating.Generate(f.Random.Number(1, 5))) - .RuleFor(x => x.Contributors, f => mediaContributor.Generate(f.Random.Number(1, 5))); + .RuleFor(x => x.LibraryId, libraryId ?? _fixture.Create()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Metadata, metadata ?? metadataFaker) + .RuleFor(x => x.Format, format ?? (includeOptionalProperties ? _fixture.Create() : null)) + .RuleFor(x => x.Edition, f => edition ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.VolumeNumber, volumeNumber ?? (includeOptionalProperties ? (float?)_random.Next(1, 3) : null)) + .RuleFor(x => x.Series, series) + .RuleFor(x => x.ASIN, f => asin ?? (includeOptionalProperties ? f.Random.String2(10) : null)) + .RuleFor(x => x.GoodreadsId, goodreadsId ?? (includeOptionalProperties ? _random.Next(100000, 500000).ToString() : null)) + .RuleFor(x => x.LCCN, f => lccn ?? (includeOptionalProperties ? CreateLccn(f) : null)) + .RuleFor(x => x.OCLCNumber, f => oclcNumber ?? (includeOptionalProperties ? CreateOclcNumber(f) : null)) + .RuleFor(x => x.OpenLibraryId, f => openLibraryId ?? (includeOptionalProperties ? CreateOpenLibraryId(f) : null)) + .RuleFor(x => x.LibraryThingId, f => libraryThingId ?? (includeOptionalProperties ? f.Random.String2(f.Random.Number(1, 50)) : null)) + .RuleFor(x => x.GoogleBooksId, f => googleBooksId ?? (includeOptionalProperties ? CreateGoogleBooksId(f) : null)) + .RuleFor(x => x.BarnesAndNobleId, f => barnesAndNobleId ?? (includeOptionalProperties ? f.Random.String2(10, "0123456789") : null)) + .RuleFor(x => x.AppleBooksId, f => appleBooksId ?? (includeOptionalProperties ? $"id{f.Random.Number(1, 999999)}" : null)) + .RuleFor(p => p.ISBNs, f => isbns ?? (includeOptionalProperties ? isbn.Generate(f.Random.Number(1, 5)) : null)) + .RuleFor(p => p.Ratings, f => ratings ?? (includeOptionalProperties ? rating.Generate(f.Random.Number(1, 5)) : null)) + .RuleFor(x => x.Contributors, f => contributors ?? (includeOptionalProperties ? mediaContributor.Generate(f.Random.Number(1, 5)) : null)); + } + + /// + /// Generates a random LCCN (Library of Congress Control Number). + /// + /// The faker used to generate the value. + /// The generated LCCN. + private static string CreateLccn(Faker faker) + { + string letters = new([.. Enumerable.Range(0, faker.Random.Number(0, 3)).Select(_ => faker.Random.Char('a', 'z'))]); + string digits = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return letters + digits; + } + + /// + /// Generates a random OCLC number (WorldCat identifier). + /// + /// The faker used to generate the value. + /// The generated OCLC number. + private static string CreateOclcNumber(Faker faker) + { + string[] prefixes = ["ocm", "ocn", "on", "(OCoLC)"]; + string prefix = faker.Random.ArrayElement(prefixes); + string number; + switch (prefix) + { + case "ocm": + number = faker.Random.String2(8, "0123456789"); + break; + case "ocn": + number = faker.Random.String2(faker.Random.Number(9, 11), "0123456789"); + break; + case "on": + number = faker.Random.String2(10, "0123456789"); + break; + case "(OCoLC)": + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + break; + default: + number = faker.Random.String2(faker.Random.Number(8, 10), "0123456789"); + return number; + } + return prefix + number; + } + + /// + /// Generates a random Open Library Id. + /// + /// The faker used to generate the value. + /// The generated Open Library Id. + private static string CreateOpenLibraryId(Faker faker) + { + int firstDigit = faker.Random.Number(1, 9); + string remainingDigits = faker.Random.String2(faker.Random.Number(0, 6), "0123456789"); + char suffix = faker.Random.ArrayElement(['A', 'M', 'W']); + return $"OL{firstDigit}{remainingDigits}{suffix}"; + } + + /// + /// Generates a random Google Books Id. + /// + /// The faker used to generate the value. + /// The generated Google Books Id. + private static string CreateGoogleBooksId(Faker faker) + { + const string VALID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + return new string([.. Enumerable.Repeat(VALID_CHARS, 12).Select(s => s[faker.Random.Number(VALID_CHARS.Length - 1)])]); } } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs index ea878333..b7ea3062 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestFixture.cs @@ -26,7 +26,7 @@ public class GetBooksLiteRequestFixture /// Optional. The maximum number of books to retrieve per page. /// Optional. The search term used to filter results. /// Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker. - /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + /// Optional. Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// Optional. The name of the field by which to sort the results. /// Optional. The direction in which to sort the results. /// The created . @@ -36,7 +36,7 @@ public class GetBooksLiteRequestFixture int? perPage = null, string? searchTerm = null, string? filterAlphaKey = null, - bool ignoreThePrefixForAlphaPicker = false, + bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null) { @@ -46,7 +46,7 @@ public class GetBooksLiteRequestFixture PerPage: perPage ?? _faker.Random.Number(1, 200), SearchTerm: searchTerm ?? _faker.Lorem.Word(), FilterAlphaKey: filterAlphaKey, - IgnoreThePrefixForAlphaPicker: ignoreThePrefixForAlphaPicker, + ShouldIgnoreThePrefixForAlphaPicker: shouldIgnoreThePrefixForAlphaPicker, SortBy: sortBy ?? _faker.Lorem.Word(), SortOrder: sortOrder ?? _faker.PickRandom() ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs index a3112552..9ee8b49e 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseFixture.cs @@ -15,6 +15,8 @@ namespace Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnai [ExcludeFromCodeCoverage] public class ThumbnailResponseFixture { + private readonly Faker _faker = new(); + /// /// Creates a random valid . /// @@ -23,10 +25,9 @@ public class ThumbnailResponseFixture /// The created . public ThumbnailResponse Create(ImageType? type = null, byte[]? bytes = null) { - Faker faker = new(); return new ThumbnailResponse( - type ?? faker.PickRandom(), - bytes ?? faker.Random.Bytes(20) + type ?? _faker.PickRandom(), + bytes ?? _faker.Random.Bytes(20) ); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs index da74bf7d..e7dd6e27 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs @@ -40,7 +40,8 @@ public class BookResponseFixture WrittenContentMetadataDto? metadata = null, BookFormat? format = null, MetadataStatus? metadataStatus = null, - DateTime? createdOnUtc = null) + DateTime? createdOnUtc = null, + string? coverPath = null) { DateTime resolvedCreatedOnUtc = createdOnUtc ?? _faker.Date.Past().ToUniversalTime(); return new BookResponse( @@ -70,7 +71,8 @@ public class BookResponseFixture _faker.Date.Recent().ToUniversalTime(), _faker.Company.CompanyName(), resolvedCreatedOnUtc, - _faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null + _faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : null, + coverPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null) ); } diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs index 19f28754..5b4a81cf 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookFixture.cs @@ -50,7 +50,7 @@ public class BookFixture _fixture.Create(), _fixture.Create(), _fixture.Create>(), - _fixture.Create>(), + _fixture.Create>(), _fixture.Create>(), _fixture.Create>(), _fixture.Create>(), diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs index fa0c6533..43c545af 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/ThemeEngineOptionsDtoFixture.cs @@ -15,6 +15,8 @@ namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; [ExcludeFromCodeCoverage] public class ThemeEngineOptionsDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a random valid . /// @@ -35,16 +37,15 @@ public class ThemeEngineOptionsDtoFixture long? maxSingleFileBytes = null, int? maxEntries = null) { - Faker faker = new(); return new ThemeEngineOptionsDto { - StoragePath = storagePath ?? faker.System.DirectoryPath(), - BundledThemesPath = bundledThemesPath ?? faker.System.DirectoryPath(), - DefaultThemeId = defaultThemeId ?? faker.Lorem.Word(), - MaxArchiveBytes = maxArchiveBytes ?? faker.Random.Long(1_000_000, 100_000_000), - MaxExpandedBytes = maxExpandedBytes ?? faker.Random.Long(10_000_000, 500_000_000), - MaxSingleFileBytes = maxSingleFileBytes ?? faker.Random.Long(1_000_000, 50_000_000), - MaxEntries = maxEntries ?? faker.Random.Int(1, 1000) + StoragePath = storagePath ?? _faker.System.DirectoryPath(), + BundledThemesPath = bundledThemesPath ?? _faker.System.DirectoryPath(), + DefaultThemeId = defaultThemeId ?? _faker.Lorem.Word(), + MaxArchiveBytes = maxArchiveBytes ?? _faker.Random.Long(1_000_000, 100_000_000), + MaxExpandedBytes = maxExpandedBytes ?? _faker.Random.Long(10_000_000, 500_000_000), + MaxSingleFileBytes = maxSingleFileBytes ?? _faker.Random.Long(1_000_000, 50_000_000), + MaxEntries = maxEntries ?? _faker.Random.Int(1, 1000) }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index 4aa21845..2b3c67cf 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -10,7 +10,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; @@ -29,6 +28,7 @@ public class StubApiHttpClient : IApiHttpClient private readonly Dictionary> _postResponseFactories = []; private readonly Dictionary> _putResponseFactories = []; private readonly HashSet _deleteSuccessEndpoints = []; + private BlobDataDto? _blobResponse; /// /// Gets the authorization response returned for the auth/get-authorization endpoint. @@ -167,6 +167,15 @@ public class StubApiHttpClient : IApiHttpClient _deleteSuccessEndpoints.Add(endpoint); } + /// + /// Registers the blob response returned when a blob endpoint is called. + /// + /// The blob response to return. + public void RegisterBlobResponse(BlobDataDto blob) + { + _blobResponse = blob; + } + /// /// Resets all registered responses and captured requests, keeping only the default responses. /// @@ -176,6 +185,7 @@ public class StubApiHttpClient : IApiHttpClient _postResponseFactories.Clear(); _putResponseFactories.Clear(); _deleteSuccessEndpoints.Clear(); + _blobResponse = null; GetEndpointsCalled.Clear(); PostRequests.Clear(); PutRequests.Clear(); @@ -222,6 +232,8 @@ public class StubApiHttpClient : IApiHttpClient /// A model containing the deserialized blob. public Task GetBlobAsync(string endpoint, CancellationToken cancellationToken = default) { + if (_blobResponse is not null) + return Task.FromResult(_blobResponse); throw new NotSupportedException("Blob retrieval is not supported by the test stub."); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs index 858f0dc7..855fc922 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Authorization/RoleDtoFixture.cs @@ -15,6 +15,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; [ExcludeFromCodeCoverage] public class RoleDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -23,10 +25,9 @@ public class RoleDtoFixture /// A configured instance. public RoleDto Create(Guid? id = null, string? roleName = null) { - Faker faker = new(); return new RoleDto( Id: id ?? Guid.NewGuid(), - RoleName: roleName ?? faker.Commerce.Department() + RoleName: roleName ?? _faker.Commerce.Department() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs index 7fa24e10..a6265310 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeInfoDtoFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Presentation.Web.Common.DTO.Themes; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -15,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeInfoDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -37,16 +38,15 @@ public class ThemeInfoDtoFixture bool? isBundled = null, bool? isDeleted = null) { - Faker faker = new(); return new ThemeInfoDto( - Id: id ?? faker.Lorem.Word(), - Name: name ?? faker.Commerce.ProductName(), - Description: description ?? faker.Lorem.Sentence(), - Author: author ?? faker.Name.FullName(), - Version: version ?? faker.System.Semver(), - PreviewUrl: previewUrl ?? $"/theme-assets/{faker.Lorem.Word()}/preview.png", - IsBundled: isBundled ?? faker.Random.Bool(), - IsDeleted: isDeleted ?? faker.Random.Bool() + Id: id ?? _faker.Lorem.Word(), + Name: name ?? _faker.Commerce.ProductName(), + Description: description ?? _faker.Lorem.Sentence(), + Author: author ?? _faker.Name.FullName(), + Version: version ?? _faker.System.Semver(), + PreviewUrl: previewUrl ?? $"/theme-assets/{_faker.Lorem.Word()}/preview.png", + IsBundled: isBundled ?? _faker.Random.Bool(), + IsDeleted: isDeleted ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs index 5016ae36..b2bb7ae1 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeNavMenuDtoFixture.cs @@ -15,6 +15,9 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeNavMenuDtoFixture { + private readonly Faker _faker = new(); + private readonly ThemeNavSectionDtoFixture _themeNavSectionDtoFixture = new(); + /// /// Creates a new instance with randomized test data. /// @@ -27,57 +30,14 @@ public class ThemeNavMenuDtoFixture IReadOnlyList? mobileSections = null, IReadOnlyList? menubarSections = null) { - Faker faker = new(); - ThemeNavSectionDto[] generatedSections = [CreateSection()]; + ThemeNavSectionDto[] generatedSections = [_themeNavSectionDtoFixture.Create()]; return new ThemeNavMenuDto( - SiteName: siteName ?? faker.Company.CompanyName(), + SiteName: siteName ?? _faker.Company.CompanyName(), MobileSections: mobileSections ?? generatedSections, MenubarSections: menubarSections ?? generatedSections ); } - /// - /// Creates a single instance with randomized test data. - /// - /// Optional label of the section. - /// Optional entries of the section. - /// A configured instance. - public ThemeNavSectionDto CreateSection(string? label = null, IReadOnlyList? items = null) - { - Faker faker = new(); - return new ThemeNavSectionDto( - Label: label ?? faker.Lorem.Word(), - Items: items ?? [CreateEntry()] - ); - } - - /// - /// Creates a single instance with randomized test data. - /// - /// Optional label of the entry. - /// Optional URL of the link, or for a submenu. - /// Whether to set , or when . - /// Optional CSS classes of the link. - /// Whether to set , or when . - /// Optional child links of a submenu. - /// A configured instance. - public ThemeNavEntryDto CreateEntry( - string? label = null, - string? url = null, - bool includeUrl = false, - string? cssClass = null, - bool includeCssClass = false, - IReadOnlyList? children = null) - { - Faker faker = new(); - return new ThemeNavEntryDto( - Label: label ?? faker.Lorem.Word(), - Url: includeUrl ? (url ?? faker.Internet.Url()) : null, - CssClass: includeCssClass ? (cssClass ?? faker.Lorem.Word()) : null, - Children: children ?? [] - ); - } - /// /// Creates multiple instances with randomized test data. /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs index 684f568a..eabcf668 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemePageDtoFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Presentation.Web.Common.DTO.Themes; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -15,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemePageDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -29,12 +30,11 @@ public class ThemePageDtoFixture string? description = null, IReadOnlyDictionary? pageData = null) { - Faker faker = new(); return new ThemePageDto { - PageKey = pageKey ?? faker.Lorem.Word(), - Title = title ?? faker.Lorem.Sentence(), - Description = description ?? faker.Lorem.Sentence(), + PageKey = pageKey ?? _faker.Lorem.Word(), + Title = title ?? _faker.Lorem.Sentence(), + Description = description ?? _faker.Lorem.Sentence(), PageData = pageData ?? new Dictionary() }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs index 45a22191..9e9717de 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeRenderDocumentDtoFixture.cs @@ -14,6 +14,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeRenderDocumentDtoFixture { + private readonly Faker _faker = new(); private readonly ThemeInfoDtoFixture _themeInfoDtoFixture = new(); /// @@ -22,12 +23,13 @@ public class ThemeRenderDocumentDtoFixture /// Optional metadata of the resolved theme. /// Optional raw template source to render. /// A configured instance. - public ThemeRenderDocumentDto Create(ThemeInfoDto? theme = null, string? template = null) + public ThemeRenderDocumentDto Create( + ThemeInfoDto? theme = null, + string? template = null) { - Faker faker = new(); return new ThemeRenderDocumentDto( Theme: theme ?? _themeInfoDtoFixture.Create(), - Template: template ?? faker.Lorem.Paragraph() + Template: template ?? _faker.Lorem.Paragraph() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs index ab1803a5..36901ca5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeResponseDtoFixture.cs @@ -16,6 +16,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeResponseDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -48,19 +50,18 @@ public class ThemeResponseDtoFixture DateTime? installedAtUtc = null, bool? isDeleted = null) { - Faker faker = new(); return new ThemeResponseDto( Id: id ?? Guid.NewGuid(), - ThemeId: themeId ?? faker.Lorem.Word(), - Name: name ?? faker.Commerce.ProductName(), - Description: description ?? faker.Lorem.Sentence(), - Author: author ?? faker.Name.FullName(), - Version: version ?? faker.System.Semver(), - PreviewPath: includePreviewPath ? (previewPath ?? (faker.Random.Bool() ? faker.System.FilePath() : null)) : null, + ThemeId: themeId ?? _faker.Lorem.Word(), + Name: name ?? _faker.Commerce.ProductName(), + Description: description ?? _faker.Lorem.Sentence(), + Author: author ?? _faker.Name.FullName(), + Version: version ?? _faker.System.Semver(), + PreviewPath: includePreviewPath ? (previewPath ?? (_faker.Random.Bool() ? _faker.System.FilePath() : null)) : null, InstallSource: installSource ?? ThemeInstallSource.Uploaded, - IsCurrent: includeIsCurrent ? (isCurrent ?? (faker.Random.Bool() ? true : null)) : null, - InstalledAtUtc: installedAtUtc ?? faker.Date.Recent(), - IsDeleted: isDeleted ?? faker.Random.Bool() + IsCurrent: includeIsCurrent ? (isCurrent ?? (_faker.Random.Bool() ? true : null)) : null, + InstalledAtUtc: installedAtUtc ?? _faker.Date.Recent(), + IsDeleted: isDeleted ?? _faker.Random.Bool() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs index 03f0032e..71ad89cc 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeSettingsResponseDtoFixture.cs @@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeSettingsResponseDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -24,10 +26,9 @@ public class ThemeSettingsResponseDtoFixture long? maxArchiveBytes = null, string? defaultThemeId = null) { - Faker faker = new(); return new ThemeSettingsResponseDto( - MaxArchiveBytes: maxArchiveBytes ?? faker.Random.Long(1024 * 1024, 256 * 1024 * 1024), - DefaultThemeId: defaultThemeId ?? faker.Lorem.Word() + MaxArchiveBytes: maxArchiveBytes ?? _faker.Random.Long(1024 * 1024, 256 * 1024 * 1024), + DefaultThemeId: defaultThemeId ?? _faker.Lorem.Word() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs index fe00f0b4..ed45d6f5 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Presentation.Web.Common.DTO.Themes; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -15,6 +14,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; [ExcludeFromCodeCoverage] public class ThemeTemplateResponseDtoFixture { + private readonly Faker _faker = new(); private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); /// @@ -27,10 +27,9 @@ public class ThemeTemplateResponseDtoFixture ThemeResponseDto? theme = null, string? template = null) { - Faker faker = new(); return new ThemeTemplateResponseDto( Theme: theme ?? _themeResponseDtoFixture.Create(), - Template: template ?? faker.Lorem.Paragraph() + Template: template ?? _faker.Lorem.Paragraph() ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs index e6a005bf..99d99d04 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Models/SectionModelFixture.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Bogus; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -14,15 +13,17 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Models; [ExcludeFromCodeCoverage] public class SectionModelFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional text rendered by the section. /// A configured instance. - public SectionModel Create(string? text = null) + public SectionModel Create( + string? text = null) { - Faker faker = new(); - return new SectionModel { Text = text ?? faker.Lorem.Word() }; + return new SectionModel { Text = text ?? _faker.Lorem.Word() }; } /// diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs index 0057f6d2..56abddbb 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Authorization/AddRoleRequestFixture.cs @@ -15,17 +15,20 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; [ExcludeFromCodeCoverage] public class AddRoleRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional name of the role. /// Optional collection of permission identifiers. /// A configured instance. - public AddRoleRequest Create(string? roleName = null, List? permissions = null) + public AddRoleRequest Create( + string? roleName = null, + List? permissions = null) { - Faker faker = new(); return new AddRoleRequest( - RoleName: roleName ?? faker.Commerce.Department(), + RoleName: roleName ?? _faker.Commerce.Department(), Permissions: permissions ?? [Guid.NewGuid(), Guid.NewGuid()] ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs index 7bf7557f..01dfbaaa 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Libraries/GetBooksLiteRequestFixture.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Bogus; using Lumina.Presentation.Web.Common.Enums.Common; using Lumina.Presentation.Web.Common.Requests.Libraries; using System; @@ -24,7 +23,7 @@ public class GetBooksLiteRequestFixture /// Optional number of books to retrieve per page. /// Optional search term used to filter results. /// Optional alpha key used to filter the results. - /// Whether the leading "The " prefix is ignored by the alpha picker. + /// Whether the leading "The " prefix is ignored by the alpha picker. /// Optional name of the field by which to sort the results. /// Optional direction in which to sort the results. /// A configured instance. @@ -34,7 +33,7 @@ public class GetBooksLiteRequestFixture int? perPage = null, string? searchTerm = null, string? filterAlphaKey = null, - bool ignoreThePrefixForAlphaPicker = false, + bool shouldIgnoreThePrefixForAlphaPicker = false, string? sortBy = null, SortOrder? sortOrder = null) { @@ -45,7 +44,7 @@ public class GetBooksLiteRequestFixture PerPage = perPage, SearchTerm = searchTerm, FilterAlphaKey = filterAlphaKey, - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker, + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker, SortBy = sortBy, SortOrder = sortOrder }; diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs index fe08c93e..a9c5a850 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/Authentication/LoginViewRequestFixture.cs @@ -14,16 +14,18 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authe [ExcludeFromCodeCoverage] public class LoginViewRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional URL to return to, after login. /// A configured instance. - public LoginViewRequest Create(string? returnUrl = null) + public LoginViewRequest Create( + string? returnUrl = null) { - Faker faker = new(); return new LoginViewRequest( - ReturnUrl: returnUrl ?? $"/{faker.Random.AlphaNumeric(8)}" + ReturnUrl: returnUrl ?? $"/{_faker.Random.AlphaNumeric(8)}" ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs index a0e75deb..ada59d24 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/ChangePasswordRequestFixture.cs @@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; [ExcludeFromCodeCoverage] public class ChangePasswordRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -22,13 +24,16 @@ public class ChangePasswordRequestFixture /// Optional new password. /// Optional confirmation of the new password. /// A configured instance. - public ChangePasswordRequest Create(string? username = null, string? currentPassword = null, string? newPassword = null, string? newPasswordConfirm = null) + public ChangePasswordRequest Create( + string? username = null, + string? currentPassword = null, + string? newPassword = null, + string? newPasswordConfirm = null) { - Faker faker = new(); - string generatedNewPassword = newPassword ?? faker.Internet.Password(12); + string generatedNewPassword = newPassword ?? _faker.Internet.Password(12); return new ChangePasswordRequest( - Username: username ?? faker.Internet.UserName(), - CurrentPassword: currentPassword ?? faker.Internet.Password(12), + Username: username ?? _faker.Internet.UserName(), + CurrentPassword: currentPassword ?? _faker.Internet.Password(12), NewPassword: generatedNewPassword, NewPasswordConfirm: newPasswordConfirm ?? generatedNewPassword ); diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs index 9d39afdb..ff93376b 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/LoginRequestFixture.cs @@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; [ExcludeFromCodeCoverage] public class LoginRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -22,12 +24,15 @@ public class LoginRequestFixture /// Optional TOTP code. /// Optional URL to return to, after login. /// A configured instance. - public LoginRequest Create(string? username = null, string? password = null, string? totpCode = null, string? returnUrl = null) + public LoginRequest Create( + string? username = null, + string? password = null, + string? totpCode = null, + string? returnUrl = null) { - Faker faker = new(); return new LoginRequest( - Username: username ?? faker.Internet.UserName(), - Password: password ?? faker.Internet.Password(12), + Username: username ?? _faker.Internet.UserName(), + Password: password ?? _faker.Internet.Password(12), TotpCode: totpCode, ReturnUrl: returnUrl ); diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs index cb8f2ce5..5ece6620 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RecoverPasswordRequestFixture.cs @@ -14,17 +14,20 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; [ExcludeFromCodeCoverage] public class RecoverPasswordRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional username. /// Optional TOTP code. /// A configured instance. - public RecoverPasswordRequest Create(string? username = null, string? totpCode = null) + public RecoverPasswordRequest Create( + string? username = null, + string? totpCode = null) { - Faker faker = new(); return new RecoverPasswordRequest( - Username: username ?? faker.Internet.UserName(), + Username: username ?? _faker.Internet.UserName(), TotpCode: totpCode ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs index a6596a66..eecebc32 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/UsersManagement/RegisterRequestFixture.cs @@ -14,6 +14,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; [ExcludeFromCodeCoverage] public class RegisterRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -23,12 +25,16 @@ public class RegisterRequestFixture /// Optional registration type, e.g. "Admin" or "User". /// Whether two-factor authentication is enabled for the account. /// A configured instance. - public RegisterRequest Create(string? username = null, string? password = null, string? passwordConfirm = null, string? registrationType = "User", bool use2fa = true) + public RegisterRequest Create( + string? username = null, + string? password = null, + string? passwordConfirm = null, + string? registrationType = "User", + bool use2fa = true) { - Faker faker = new(); - string generatedPassword = password ?? faker.Internet.Password(12); + string generatedPassword = password ?? _faker.Internet.Password(12); return new RegisterRequest( - Username: username ?? faker.Internet.UserName(), + Username: username ?? _faker.Internet.UserName(), Password: generatedPassword, PasswordConfirm: passwordConfirm ?? generatedPassword, RegistrationType: registrationType, diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs index 533da3dc..6d6e3966 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Seed; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -30,6 +31,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); /// /// Gets the username of the currently created test user. @@ -65,17 +67,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); // create test user - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = TestUsername!, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); @@ -127,17 +120,8 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable IDataSeedService dataSeedService = scope.ServiceProvider.GetRequiredService(); // create test user - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = TestUsername!, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: TestUsername!, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs index 36436bda..9a3606d7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRoleEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; @@ -28,6 +29,7 @@ public class DeleteRoleEndpointTests : IClassFixture(); // Create a test role first - RoleEntity role = new() - { - Id = Guid.NewGuid(), - RoleName = "TestRole", - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole"); dbContext.Roles.Add(role); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs index 88aaf90b..a7130f4d 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.DataAccess.Core.UoW; @@ -33,6 +35,8 @@ public class UpdateRoleEndpointTests : IClassFixture(); - RoleEntity role = new() - { - Id = Guid.NewGuid(), - RoleName = "TestRole", - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole"); dbContext.Roles.Add(role); await dbContext.SaveChangesAsync(); PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)]; - UpdateRoleRequest request = new( - RoleId: role.Id, - RoleName: "UpdatedRole", - Permissions: permissions.Select(p => p.Id).ToList() + UpdateRoleRequest request = _updateRoleRequestFixture.Create( + roleId: role.Id, + roleName: "UpdatedRole", + permissions: [.. permissions.Select(p => p.Id)] ); // Act @@ -107,10 +105,10 @@ public class UpdateRoleEndpointTests : IClassFixture - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a and returns its Id. - /// - /// The Id of the seeded user. - private async Task SeedUserAsync() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid userId = Guid.NewGuid(); - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = $"otheruser_{Guid.NewGuid()}", - Password = "TestPass123!", - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); - await dbContext.SaveChangesAsync(); - return userId; - } - /// /// Disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index cc092581..9fad8b58 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -1,10 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -16,9 +18,7 @@ using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; using System.Threading.Tasks; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; #endregion namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; @@ -36,6 +36,9 @@ public class GetBooksLiteEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -117,7 +120,7 @@ public class GetBooksLiteEndpointTests : IClassFixture(); - dbContext.Books.Add(new BookEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - Path = $"/books/{Guid.NewGuid()}.epub", - Title = title, - OriginalTitle = originalTitle, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Books.Add(_bookEntityFixture.Create(libraryId: libraryId, title: title, originalTitle: originalTitle, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false)); await dbContext.SaveChangesAsync(); } + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a and returns its Id. + /// + /// The Id of the seeded user. + private async Task SeedUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + return userId; + } + /// /// Gets the Id of the currently authenticated test user. /// @@ -351,54 +372,6 @@ public class GetBooksLiteEndpointTests : IClassFixture - /// Seeds a owned by . - /// - /// The Id of the library to seed. - /// The Id of the user that owns the library. - /// A task representing the asynchronous operation. - private async Task SeedLibraryAsync(Guid libraryId, Guid userId) - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); - await dbContext.SaveChangesAsync(); - } - - /// - /// Seeds a and returns its Id. - /// - /// The Id of the seeded user. - private async Task SeedUserAsync() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - Guid userId = Guid.NewGuid(); - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = $"otheruser_{Guid.NewGuid()}", - Password = "TestPass123!", - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); - await dbContext.SaveChangesAsync(); - return userId; - } - /// /// Disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index 9a34d748..8fb18606 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; @@ -25,6 +26,7 @@ public class CheckInitializationEndpointTests : IClassFixture(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = new PasswordHashService().HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index 73b9de47..b01b5441 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -32,6 +34,8 @@ public class SetupApplicationEndpointTests : IClassFixture(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = new PasswordHashService().HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, // TODO: test default role and permissions? - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + // TODO: test default role and permissions? + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index 7975eba1..a1118b53 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; @@ -9,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Json; @@ -34,6 +33,7 @@ public class GetPluginsEndpointTests : IClassFixture _seededPluginIds = []; + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -95,37 +95,11 @@ public class GetPluginsEndpointTests : IClassFixture(); - Guid userId = GetCurrentUserId(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); _seededPluginIds.Add(pluginId); } - /// - /// Gets the Id of the currently authenticated test user. - /// - /// The Id of the authenticated test user. - private Guid GetCurrentUserId() - { - using IServiceScope scope = _apiFactory.Services.CreateScope(); - LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); - return user.Id; - } - /// /// Removes the seeded plugins and disposes API factory resources. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index 35c5ba2f..9925e8b0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -29,6 +30,7 @@ public class ChangePasswordEndpointTests : IClassFixture, private HttpClient _client; private readonly AuthenticatedLuminaApiFactory _apiFactory; private readonly PasswordHashService _hashService = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); private readonly ICryptographyService _cryptographyService; private readonly TotpTokenGenerator _totpTokenGenerator = new(); private readonly JsonSerializerOptions _jsonOptions = new() @@ -70,9 +74,9 @@ public class LoginEndpointTests : IClassFixture, { // Arrange UserEntity user = await CreateTestUser(); - LoginRequest request = new( - Username: user.Username, - Password: "TestPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!" ); // Act @@ -101,10 +105,10 @@ public class LoginEndpointTests : IClassFixture, Totp totp = new(totpSecret); string validTotpCode = totp.ComputeTotp(DateTime.UtcNow); - LoginRequest request = new( - Username: user.Username, - Password: "TestPass123!", - TotpCode: validTotpCode + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + totpCode: validTotpCode ); // Act @@ -129,9 +133,9 @@ public class LoginEndpointTests : IClassFixture, { // Arrange UserEntity user = await CreateTestUserWithTempPassword(); - LoginRequest request = new( - Username: user.Username, - Password: "TempPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TempPass123!" ); // Act @@ -155,9 +159,9 @@ public class LoginEndpointTests : IClassFixture, { // Arrange UserEntity user = await CreateTestUserWithExpiredTempPassword(); - LoginRequest request = new( - Username: user.Username, - Password: "TempPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TempPass123!" ); // Act @@ -183,9 +187,9 @@ public class LoginEndpointTests : IClassFixture, { // Arrange UserEntity user = await CreateTestUser(); - LoginRequest request = new( - Username: user.Username, - Password: "WrongPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "WrongPass123!" ); // Act @@ -211,10 +215,10 @@ public class LoginEndpointTests : IClassFixture, { // Arrange UserEntity user = await CreateTestUserWithTotp(); - LoginRequest request = new( - Username: user.Username, - Password: "TestPass123!", - TotpCode: "000000" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + totpCode: "000000" ); // Act @@ -240,94 +244,73 @@ public class LoginEndpointTests : IClassFixture, Assert.Contains("InvalidTotpCode", errors["General.Validation"]); } + /// + /// Creates a test user without a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUser() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); return user; } + /// + /// Creates a test user with a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUserWithTotp() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); return user; } + /// + /// Creates a test user with a temporary password in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUserWithTempPassword() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), - TempPasswordCreated = DateTime.UtcNow, - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")); + user.TempPasswordCreated = DateTime.UtcNow; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); return user; } + /// + /// Creates a test user with an expired temporary password in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUserWithExpiredTempPassword() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")), - TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16), // expired (> 15 minutes old) - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + user.TempPassword = Uri.EscapeDataString(_hashService.HashString("TempPass123!")); + user.TempPasswordCreated = DateTime.UtcNow.AddMinutes(-16); // expired (> 15 minutes old) dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 1e9e1c9f..f0f554c4 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -35,6 +36,7 @@ public class RecoverPasswordEndpointTests : IClassFixture(); - UserEntity userWithoutTotp = new() - { - Id = Guid.NewGuid(), - Username = "userwithoutotp2", - Password = _hashService.HashString("OldPass123!"), - TotpSecret = null, // No TOTP configured - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity userWithoutTotp = _userEntityFixture.Create(username: "userwithoutotp2", password: _hashService.HashString("OldPass123!")); + userWithoutTotp.TotpSecret = null; // No TOTP configured dbContext.Users.Add(userWithoutTotp); await dbContext.SaveChangesAsync(); } @@ -307,47 +299,35 @@ public class RecoverPasswordEndpointTests : IClassFixture(exception); } + /// + /// Creates a test user with a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateUserWithTotp() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("OldPass123!"), - TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!")); + user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); return user; } + /// + /// Creates a test user without a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateUserWithoutTotp() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = _hashService.HashString("OldPass123!"), - TotpSecret = null, - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("OldPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 2a9d9bfd..58917bf5 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -29,6 +31,8 @@ public class RegisterEndpointTests : IClassFixture + /// Creates a test user in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUser() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = _testUsername, - Password = new PasswordHashService().HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: new PasswordHashService().HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs index cea07a3b..6064c214 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorizationEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.DataAccess.Core.UoW; @@ -34,6 +36,11 @@ public class GetAuthorizationEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -78,7 +85,7 @@ public class GetAuthorizationEndpointTests : IClassFixture userPermission.Permission) .FirstAsync(user => user.Username == _apiFactory.TestUsername); await AddRolesAndPermissionsToUser(user, dbContext); - GetAuthorizationRequest request = new(user.Id); + GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(userId: user.Id); // Act HttpResponseMessage response = await _client.GetAsync($"/api/v1/auth/get-authorization?userId={request.UserId}"); @@ -100,7 +107,7 @@ public class GetAuthorizationEndpointTests : IClassFixture(exception); } - private static async Task AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext) + private async Task AddRolesAndPermissionsToUser(UserEntity existingUser, LuminaDbContext dbContext) { // create and save role and permission first - RoleEntity adminRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; - - PermissionEntity viewUsersPermission = new() - { - Id = Guid.NewGuid(), - PermissionName = AuthorizationPermission.CanViewUsers, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); + PermissionEntity viewUsersPermission = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers); await dbContext.Roles.AddAsync(adminRole); await dbContext.Permissions.AddAsync(viewUsersPermission); await dbContext.SaveChangesAsync(); // create role permission - RolePermissionEntity rolePermission = new() - { - Id = Guid.NewGuid(), - Permission = viewUsersPermission, - PermissionId = viewUsersPermission.Id, - Role = adminRole, - RoleId = adminRole.Id, - CreatedBy = existingUser.Id, - CreatedOnUtc = DateTime.UtcNow - }; + RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(role: adminRole, permission: viewUsersPermission); await dbContext.RolePermissions.AddAsync(rolePermission); await dbContext.SaveChangesAsync(); @@ -207,16 +192,7 @@ public class GetAuthorizationEndpointTests : IClassFixture(); // create a non-admin role first - RoleEntity editorRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Editor", - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor"); dbContext.Roles.Add(editorRole); await dbContext.SaveChangesAsync(); // create test user - UserEntity user = new() - { - Id = Guid.NewGuid(), - Username = "TestUser", - Password = "HashedPassword", - UserRole = null, - UserPermissions = [], - Libraries = [], - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: "TestUser", password: "HashedPassword"); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); PermissionEntity[] permissions = [.. dbContext.Permissions.Take(2)]; - UpdateUserRoleAndPermissionsRequest request = new( - UserId: user.Id, - RoleId: editorRole.Id, - Permissions: permissions.Select(p => p.Id).ToList() + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( + userId: user.Id, + roleId: editorRole.Id, + permissions: permissions.Select(p => p.Id).ToList() ); // Act @@ -118,10 +109,10 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture(); // create Editor role - RoleEntity editorRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Editor", - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity editorRole = _roleEntityFixture.Create(roleName: "Editor"); dbContext.Roles.Add(editorRole); await dbContext.SaveChangesAsync(); // get the admin user that was created by CreateAuthenticatedAdminClientAsync UserEntity? adminUser = dbContext.Users.FirstOrDefault(u => u.UserRole!.Role.RoleName == "Admin"); Assert.NotNull(adminUser); - UpdateUserRoleAndPermissionsRequest request = new( - UserId: adminUser!.Id, - RoleId: editorRole.Id, - Permissions: [] + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create( + userId: adminUser!.Id, + roleId: editorRole.Id, + permissions: [] ); // Act @@ -192,10 +177,10 @@ public class UpdateUserRoleAndPermissionsEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -36,8 +39,8 @@ public class GetRolesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); - RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin"), new RoleDto(Guid.NewGuid(), "User")]; + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [_roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "Admin"), _roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "User")]; _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); @@ -57,7 +60,7 @@ public class GetRolesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); // Act diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index 5f793a82..d032e6cd 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetLibraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; using System; @@ -20,6 +21,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage public class GetLibrariesEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -37,8 +39,8 @@ public class GetLibrariesEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); LibraryDto[] expectedLibraries = [ - new LibraryDto { Id = Guid.NewGuid(), Title = "Books", LibraryType = "Book" }, - new LibraryDto { Id = Guid.NewGuid(), Title = "Movies", LibraryType = "Video" } + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book"), + _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video") ]; _apiFactory.ApiClientStub.RegisterGetResponse("libraries", expectedLibraries); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index ceea2a3c..3d8485d6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; using System; @@ -22,6 +23,7 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Manage public class SaveLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -37,8 +39,9 @@ public class SaveLibraryEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - LibraryDto request = new() { Title = "New Books Library", LibraryType = "Book" }; - LibraryDto expectedResponse = new() { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }; + LibraryDto request = _libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book"); + request.Id = null; + LibraryDto expectedResponse = _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType); _apiFactory.ApiClientStub.RegisterPostResponse("libraries", expectedResponse); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") @@ -69,7 +72,7 @@ public class SaveLibraryEndpointTests : IClassFixture AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") { - Content = JsonContent.Create(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }) + Content = JsonContent.Create(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")) }; saveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 2195b24c..4b522b15 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -3,13 +3,13 @@ using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Requests.UsersManagement; using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.IntegrationTests.Common.Setup; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; @@ -27,6 +27,8 @@ namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.UsersManagemen public class LoginEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly LoginRequestFixture _loginRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -44,7 +46,7 @@ public class LoginEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -65,19 +67,15 @@ public class LoginEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - ProblemDetailsDto problemDetails = new() + ProblemDetailsDto problemDetails = _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "OneOrMoreValidationErrorsOccurred"); + problemDetails.Extensions = new Dictionary { - Title = "General.Validation", - Detail = "OneOrMoreValidationErrorsOccurred", - Extensions = new Dictionary - { - ["errors"] = CreateErrorsElement(["InvalidTotpCode"]) - } + ["errors"] = CreateErrorsElement(["InvalidTotpCode"]) }; _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(problemDetails, HttpStatusCode.UnprocessableEntity, "auth/login")); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -94,10 +92,10 @@ public class LoginEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "InvalidUsernameOrPassword"), HttpStatusCode.Forbidden, "auth/login")); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "WrongPass123!"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "WrongPass123!"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -109,6 +107,12 @@ public class LoginEndpointTests : IClassFixture Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString()); } + /// + /// Builds the login request that sends the given to the login endpoint. + /// + /// The login request to send. + /// The antiforgery token to include in the request. + /// The configured login request. private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) { HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") @@ -121,6 +125,11 @@ public class LoginEndpointTests : IClassFixture return loginRequest; } + /// + /// Builds a JSON element that contains a validation error collection carrying the given . + /// + /// The error codes to include in the collection. + /// The built JSON element. private static JsonElement CreateErrorsElement(string[] errorCodes) { using MemoryStream stream = new(); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs index 19ef44d1..fa24c6f2 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Common/Setup/LuminaApiFactory.cs @@ -1,9 +1,11 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.UoW; @@ -18,7 +20,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System.Diagnostics.CodeAnalysis; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; @@ -36,10 +37,16 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable private readonly SqliteConnection _connection; private readonly string _sharedInMemoryConnectionString; private readonly PasswordHashService _hashService = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; private const string SHARED_IN_MEMORY_CONNECTION_STRING_PREFIX = "Data Source=lumina-tests-{0};Mode=Memory;Cache=Shared"; @@ -145,43 +152,19 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - UserEntity user = new() - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); // seed a dedicated Admin role for this test user, keeping each test isolated in the shared in-memory database Guid roleId = Guid.NewGuid(); - RoleEntity role = new() - { - Id = roleId, - RoleName = "Admin", - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity role = _roleEntityFixture.Create(id: roleId, roleName: "Admin", createdBy: userId, createdOnUtc: DateTime.UtcNow); dbContext.Roles.Add(role); - dbContext.UserRoles.Add(new UserRoleEntity - { - Id = Guid.NewGuid(), - UserId = userId, - User = user, - RoleId = roleId, - Role = role, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + dbContext.UserRoles.Add(_userRoleEntityFixture.Create(userId: userId, user: user, roleId: roleId, role: role)); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); @@ -205,21 +188,12 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - UserEntity user = new() - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); @@ -277,17 +251,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } @@ -300,16 +264,7 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable { using IServiceScope scope = Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Books.Add(new BookEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - Path = $"/books/{Guid.NewGuid()}.epub", - Title = title, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Books.Add(_bookEntityFixture.Create(libraryId: libraryId, title: title, path: $"/books/{Guid.NewGuid()}.epub", includeMetadata: false)); await dbContext.SaveChangesAsync(); } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs index 6b340d28..0ddf36fb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs @@ -1,19 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; -using System.Net.Http; using System.Text; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; @@ -22,7 +19,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati /// Contains security tests for the /auth/roles route. /// [ExcludeFromCodeCoverage] -public class AddRoleEndpointTests : IClassFixture, IDisposable +public class AddRoleEndpointTests : IClassFixture, IAsyncDisposable { private readonly HttpClient _client; private readonly LuminaApiFactory _apiFactory; @@ -33,6 +30,7 @@ public class AddRoleEndpointTests : IClassFixture, IDisposable private Guid _adminUserId; private Guid _seededPermissionId; private string _createdRoleName = ""; + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -84,13 +82,7 @@ public class AddRoleEndpointTests : IClassFixture, IDisposable using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) { LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); - seedDbContext.Permissions.Add(new PermissionEntity - { - Id = _seededPermissionId, - PermissionName = AuthorizationPermission.CanDeleteUsers, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }); + seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers)); await seedDbContext.SaveChangesAsync(); } var requestBody = new @@ -118,7 +110,7 @@ public class AddRoleEndpointTests : IClassFixture, IDisposable /// /// Disposes API factory resources. /// - public void Dispose() + public async ValueTask DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -137,6 +129,6 @@ public class AddRoleEndpointTests : IClassFixture, IDisposable } dbContext.SaveChanges(); if (_adminUserId != Guid.Empty) - _apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult(); + await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs index f8ba0048..e0c082fb 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRoleEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Net; -using System.Net.Http; using System.Text; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorization.Roles; @@ -23,7 +21,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati /// Contains security tests for the /auth/roles route. /// [ExcludeFromCodeCoverage] -public class UpdateRoleEndpointTests : IClassFixture, IDisposable +public class UpdateRoleEndpointTests : IClassFixture, IAsyncDisposable { private readonly HttpClient _client; private readonly LuminaApiFactory _apiFactory; @@ -34,6 +32,9 @@ public class UpdateRoleEndpointTests : IClassFixture, IDisposa private Guid _adminUserId; private Guid _seededPermissionId; private Guid _seededRoleId; + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -49,10 +50,10 @@ public class UpdateRoleEndpointTests : IClassFixture, IDisposa public async Task UpdateRole_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange - UpdateRoleRequest requestBody = new( - RoleId: Guid.NewGuid(), - RoleName: "Editor", - Permissions: [] + UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create( + roleId: Guid.NewGuid(), + roleName: "Editor", + permissions: [] ); StringContent content = new( @@ -88,30 +89,18 @@ public class UpdateRoleEndpointTests : IClassFixture, IDisposa _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); _seededPermissionId = Guid.NewGuid(); _seededRoleId = Guid.NewGuid(); - RoleEntity seededRole = new() - { - Id = _seededRoleId, - RoleName = "ExistingRole", - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + RoleEntity seededRole = _roleEntityFixture.Create(id: _seededRoleId, roleName: "ExistingRole"); using (IServiceScope seedScope = _apiFactory.Services.CreateScope()) { LuminaDbContext seedDbContext = seedScope.ServiceProvider.GetRequiredService(); - seedDbContext.Permissions.Add(new PermissionEntity - { - Id = _seededPermissionId, - PermissionName = AuthorizationPermission.CanDeleteUsers, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }); + seedDbContext.Permissions.Add(_permissionEntityFixture.Create(id: _seededPermissionId, permissionName: AuthorizationPermission.CanDeleteUsers)); seedDbContext.Roles.Add(seededRole); await seedDbContext.SaveChangesAsync(); } - UpdateRoleRequest requestBody = new( - RoleId: seededRole.Id, - RoleName: maliciousRoleName, - Permissions: [_seededPermissionId] + UpdateRoleRequest requestBody = _updateRoleRequestFixture.Create( + roleId: seededRole.Id, + roleName: maliciousRoleName, + permissions: [_seededPermissionId] ); StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json"); @@ -134,7 +123,7 @@ public class UpdateRoleEndpointTests : IClassFixture, IDisposa /// /// Disposes API factory resources. /// - public void Dispose() + public async ValueTask DisposeAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); @@ -153,6 +142,6 @@ public class UpdateRoleEndpointTests : IClassFixture, IDisposa } dbContext.SaveChanges(); if (_adminUserId != Guid.Empty) - _apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult(); + await _apiFactory.RemoveAdminUserAsync(_adminUserId).ConfigureAwait(false); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index 7e607c93..238c06f5 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -1,19 +1,16 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.AddLibrary; @@ -26,6 +23,7 @@ public class AddLibraryEndpointTests : IClassFixture { private readonly HttpClient _client; private readonly LuminaApiFactory _apiFactory; + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -45,16 +43,16 @@ public class AddLibraryEndpointTests : IClassFixture public async Task AddLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange - AddLibraryRequest request = new( - Title: "New Library", - LibraryType: "EBook", - ContentLocations: ["C:/Media"], - CoverImage: null, - IsEnabled: true, - IsLocked: false, - DownloadMetadataFromWeb: true, - ShouldSaveMetadataInMediaDirectories: false, - ShouldSkipUnchangedDirectoriesDuringScan: true + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "New Library", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -82,16 +80,16 @@ public class AddLibraryEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - AddLibraryRequest request = new( - Title: maliciousTitle, - LibraryType: "EBook", - ContentLocations: ["C:/Media"], - CoverImage: null, - IsEnabled: true, - IsLocked: false, - DownloadMetadataFromWeb: true, - ShouldSaveMetadataInMediaDirectories: false, - ShouldSkipUnchangedDirectoriesDuringScan: true + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: maliciousTitle, + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs index 2a3e476b..1f9ff1fc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -1,21 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibrariesScan; @@ -33,6 +30,8 @@ public class CancelLibrariesScanEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -96,20 +95,12 @@ public class CancelLibrariesScanEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs index defa9e3b..bfb988e1 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -1,19 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.CancelLibraryScan; @@ -30,6 +25,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -101,17 +97,7 @@ public class CancelLibraryScanEndpointTests : IClassFixture { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index f950d534..ee2af717 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -1,19 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; @@ -30,6 +24,7 @@ public class DeleteLibraryEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -100,17 +95,7 @@ public class DeleteLibraryEndpointTests : IClassFixture { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs index e9e1557e..dd622751 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -1,21 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetEnabledLibraries; @@ -33,6 +30,8 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -97,20 +96,12 @@ public class GetEnabledLibrariesEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs index e642ca58..c433756b 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -1,21 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraries; @@ -33,6 +30,8 @@ public class GetLibrariesEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -97,20 +96,12 @@ public class GetLibrariesEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs index 8b3347ed..d9dc96f4 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -1,24 +1,20 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibrary; @@ -36,6 +32,9 @@ public class GetLibraryEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -127,17 +126,7 @@ public class GetLibraryEndpointTests : IClassFixture { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } @@ -155,20 +144,12 @@ public class GetLibraryEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs index 6cb3193f..c38d991d 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -1,18 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetLibraryScanProgress; @@ -29,6 +24,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -100,17 +96,7 @@ public class GetLibraryScanProgressEndpointTests : IClassFixture(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs index 2f24ed6b..c7f82d86 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -1,21 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; @@ -33,6 +30,8 @@ public class GetRunningLibraryScansEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -97,20 +96,12 @@ public class GetRunningLibraryScansEndpointTests : IClassFixture(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index 771ab9f2..8bcd3d50 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -1,21 +1,18 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibraries; @@ -33,6 +30,8 @@ public class ScanLibrariesEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -96,20 +95,12 @@ public class ScanLibrariesEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index 0fd9755f..20bf16d3 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -1,19 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.ScanLibrary; @@ -30,6 +25,7 @@ public class ScanLibraryEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -100,17 +96,7 @@ public class ScanLibraryEndpointTests : IClassFixture { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index 71272286..50a59428 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -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.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Management.UpdateLibrary; @@ -31,6 +29,8 @@ public class UpdateLibraryEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -47,18 +47,18 @@ public class UpdateLibraryEndpointTests : IClassFixture { // Arrange string libraryId = Guid.NewGuid().ToString(); - UpdateLibraryRequest request = new( - Id: Guid.NewGuid(), - UserId: Guid.NewGuid(), - Title: "Updated Library", - LibraryType: "EBook", - ContentLocations: ["C:/Media"], - CoverImage: null, - IsEnabled: true, - IsLocked: false, - DownloadMetadataFromWeb: true, - ShouldSaveMetadataInMediaDirectories: false, - ShouldSkipUnchangedDirectoriesDuringScan: true + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: Guid.NewGuid(), + userId: Guid.NewGuid(), + title: "Updated Library", + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -88,18 +88,18 @@ public class UpdateLibraryEndpointTests : IClassFixture Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); Guid libraryId = Guid.NewGuid(); await SeedLibraryAsync(libraryId, userId); - UpdateLibraryRequest request = new( - Id: libraryId, - UserId: userId, - Title: maliciousTitle, - LibraryType: "EBook", - ContentLocations: ["C:/Media"], - CoverImage: null, - IsEnabled: true, - IsLocked: false, - DownloadMetadataFromWeb: true, - ShouldSaveMetadataInMediaDirectories: false, - ShouldSkipUnchangedDirectoriesDuringScan: true + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create( + id: libraryId, + userId: userId, + title: maliciousTitle, + libraryType: "EBook", + contentLocations: ["C:/Media"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -132,17 +132,7 @@ public class UpdateLibraryEndpointTests : IClassFixture { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index 7b5ef556..6432c0c0 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -26,6 +28,8 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly PasswordHashService _hashService = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); private readonly string _testUsername; private readonly JsonSerializerOptions _jsonOptions = new() { @@ -49,11 +53,11 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis public async Task ChangePassword_WithoutAuthentication_ShouldReturnUnauthorizedResult() { // Arrange - ChangePasswordRequest request = new( - Username: _testUsername, - CurrentPassword: "OldPass123!", - NewPassword: "NewPass123!", - NewPasswordConfirm: "NewPass123!" + ChangePasswordRequest request = _changePasswordRequestFixture.Create( + username: _testUsername, + currentPassword: "OldPass123!", + newPassword: "NewPass123!", + newPasswordConfirm: "NewPass123!" ); // Act @@ -78,11 +82,11 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis { // Arrange UserEntity user = await CreateAndAuthenticateUser(); - ChangePasswordRequest request = new( - Username: user.Username, - CurrentPassword: "WrongPass123!", - NewPassword: "NewPass123!", - NewPasswordConfirm: "NewPass123!" + ChangePasswordRequest request = _changePasswordRequestFixture.Create( + username: user.Username, + currentPassword: "WrongPass123!", + newPassword: "NewPass123!", + newPasswordConfirm: "NewPass123!" ); // Act @@ -106,11 +110,11 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis // Arrange UserEntity user = await CreateAndAuthenticateUser(); string originalPasswordHash = user.Password; - ChangePasswordRequest request = new( - Username: maliciousUsername, - CurrentPassword: "TestPass123!", - NewPassword: "NewPass123!", - NewPasswordConfirm: "NewPass123!" + ChangePasswordRequest request = _changePasswordRequestFixture.Create( + username: maliciousUsername, + currentPassword: "TestPass123!", + newPassword: "NewPass123!", + newPasswordConfirm: "NewPass123!" ); // Act @@ -130,6 +134,12 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis Assert.Equal(originalPasswordHash, storedUser!.Password); } + /// + /// Asserts that the given is a problem detail with the expected title and detail. + /// + /// The response content to assert. + /// The expected title of the problem detail. + /// The expected detail of the problem detail. private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -138,22 +148,18 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } + /// + /// Creates a test user, authenticates it on the client, and returns it. + /// + /// The created user entity. private async Task CreateAndAuthenticateUser() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); // create test user - UserEntity user = new() - { - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs index 30b2a097..b83cf2bc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/LoginEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Infrastructure.Security; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -29,6 +30,7 @@ public class LoginEndpointTests : IClassFixture, IDisposable { private readonly PasswordHashService _hashService = new(); private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); private readonly ICryptographyService _cryptographyService; private readonly TotpTokenGenerator _totpTokenGenerator = new(); private readonly LuminaApiFactory _apiFactory; @@ -62,9 +64,9 @@ public class LoginEndpointTests : IClassFixture, IDisposable { // Arrange UserEntity user = await CreateTestUser(); - LoginRequest request = new( - Username: user.Username, - Password: "TestPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!" ); DateTimeOffset beforeRequest = DateTimeOffset.UtcNow; _client.DefaultRequestHeaders.Clear(); @@ -116,13 +118,13 @@ public class LoginEndpointTests : IClassFixture, IDisposable { // Arrange UserEntity user = await CreateTestUser(); - LoginRequest unknownUserRequest = new( - Username: "nonexistent_user", - Password: "TestPass123!" + LoginRequest unknownUserRequest = _loginRequestFixture.Create( + username: "nonexistent_user", + password: "TestPass123!" ); - LoginRequest wrongPasswordRequest = new( - Username: user.Username, - Password: "WrongPass123!" + LoginRequest wrongPasswordRequest = _loginRequestFixture.Create( + username: user.Username, + password: "WrongPass123!" ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2"); @@ -147,9 +149,9 @@ public class LoginEndpointTests : IClassFixture, IDisposable // set a fake IP for this test instance _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.3"); - LoginRequest request = new( - Username: "testuser", - Password: "TestPass123!" + LoginRequest request = _loginRequestFixture.Create( + username: "testuser", + password: "TestPass123!" ); // Act @@ -185,9 +187,9 @@ public class LoginEndpointTests : IClassFixture, IDisposable { // Arrange UserEntity legitimateUser = await CreateTestUser(); - LoginRequest request = new( - Username: maliciousUsername, - Password: "Abcd123$" + LoginRequest request = _loginRequestFixture.Create( + username: maliciousUsername, + password: "Abcd123$" ); // Act @@ -212,9 +214,9 @@ public class LoginEndpointTests : IClassFixture, IDisposable { // Arrange UserEntity user = await CreateTestUser(); - LoginRequest request = new( - Username: user.Username, - Password: "' OR '1'='1" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "' OR '1'='1" ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.11"); @@ -234,10 +236,10 @@ public class LoginEndpointTests : IClassFixture, IDisposable { // Arrange UserEntity user = await CreateTestUserWithTotp(); - LoginRequest request = new( - Username: user.Username, - Password: "TestPass123!", - TotpCode: "' OR '1'='1" + LoginRequest request = _loginRequestFixture.Create( + username: user.Username, + password: "TestPass123!", + totpCode: "' OR '1'='1" ); // Act @@ -250,6 +252,12 @@ public class LoginEndpointTests : IClassFixture, IDisposable Assert.DoesNotContain("Exception", content); } + /// + /// Asserts that the given is a problem detail with the expected title and detail. + /// + /// The response content to assert. + /// The expected title of the problem detail. + /// The expected detail of the problem detail. private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -258,6 +266,10 @@ public class LoginEndpointTests : IClassFixture, IDisposable Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } + /// + /// Creates a test user without a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUser() { using IServiceScope scope = _apiFactory.Services.CreateScope(); @@ -271,23 +283,18 @@ public class LoginEndpointTests : IClassFixture, IDisposable return user; } + /// + /// Creates a test user with a TOTP secret in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUserWithTotp() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); byte[] totpSecret = _totpTokenGenerator.GenerateSecret(); - UserEntity user = new() - { - Username = _testUsername, - Password = _hashService.HashString("TestPass123!"), - TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow - }; + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(totpSecret)); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs index 9253aa36..21bc9e5c 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RegisterEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; @@ -24,6 +25,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl { private readonly PasswordHashService _hashService = new(); private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -46,10 +48,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl public async Task Register_WhenUsernameTaken_ShouldReturnUniformConflictResponse() { // Arrange - RegistrationRequest request = new( - Username: _testUsername, - Password: "TestPass123!", - PasswordConfirm: "TestPass123!" + RegistrationRequest request = _registrationRequestFixture.Create( + username: _testUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!" ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6"); @@ -74,10 +76,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl // Arrange _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.7"); - RegistrationRequest request = new( - Username: _testUsername, - Password: "TestPass123!", - PasswordConfirm: "TestPass123!" + RegistrationRequest request = _registrationRequestFixture.Create( + username: _testUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!" ); // Act @@ -114,10 +116,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl // Arrange // note: the register validator rejects these usernames (invalid username format) with 422 before any DB access, // so the malicious username never reaches a query; the 422 assertion below is the security guarantee - RegistrationRequest request = new( - Username: maliciousUsername, - Password: "TestPass123!", - PasswordConfirm: "TestPass123!" + RegistrationRequest request = _registrationRequestFixture.Create( + username: maliciousUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!" ); // Act @@ -141,10 +143,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl public async Task Register_WithWeakPassword_ShouldBeDenied(string weakPassword) { // Arrange - RegistrationRequest request = new( - Username: _testUsername, - Password: weakPassword, - PasswordConfirm: weakPassword + RegistrationRequest request = _registrationRequestFixture.Create( + username: _testUsername, + password: weakPassword, + passwordConfirm: weakPassword ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.8"); @@ -164,10 +166,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl public async Task Register_WithValidPassword_ShouldAcceptPassword(string password) { // Arrange - RegistrationRequest request = new( - Username: _testUsername, - Password: password, - PasswordConfirm: password + RegistrationRequest request = _registrationRequestFixture.Create( + username: _testUsername, + password: password, + passwordConfirm: password ); // Act @@ -182,10 +184,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl { // Arrange await CreateTestUser(); - RegistrationRequest request = new( - Username: _testUsername, - Password: "TestPass123!", - PasswordConfirm: "TestPass123!" + RegistrationRequest request = _registrationRequestFixture.Create( + username: _testUsername, + password: "TestPass123!", + passwordConfirm: "TestPass123!" ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.9"); @@ -201,6 +203,12 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl Assert.DoesNotContain("salt", content); } + /// + /// Asserts that the given is a problem detail with the expected title and detail. + /// + /// The response content to assert. + /// The expected title of the problem detail. + /// The expected detail of the problem detail. private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) { Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); @@ -209,6 +217,10 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } + /// + /// Creates a test user in the database and returns it. + /// + /// The created user entity. private async Task CreateTestUser() { using IServiceScope scope = _apiFactory.Services.CreateScope(); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj index 3aeba81e..c4b45279 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Lumina.Presentation.Api.SecurityTests.csproj @@ -41,7 +41,10 @@ + + + diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index 7e021ace..c3519440 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -1,14 +1,12 @@ -#region ========================================================================= USING ===================================================================================== +#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Authorization; -using Lumina.Presentation.Web.Common.Responses.Authorization; using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.GetRoles; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorization.Roles.GetRoles; @@ -20,6 +18,8 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Admin.Authorizati public class GetRolesEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -50,7 +50,7 @@ public class GetRolesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "User", []); + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); // Act @@ -66,8 +66,8 @@ public class GetRolesEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.AuthorizationResponse = new GetAuthorizationResponse(Guid.NewGuid(), "Admin", []); - RoleDto[] expectedRoles = [new RoleDto(Guid.NewGuid(), "Admin")]; + _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []); + RoleDto[] expectedRoles = [_roleDtoFixture.Create(id: Guid.NewGuid(), roleName: "Admin")]; _apiFactory.ApiClientStub.RegisterGetResponse("auth/roles", expectedRoles); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs index ca7a3bf4..daa20b3e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -2,13 +2,10 @@ using Lumina.Presentation.Web.Core.Endpoints.Library.Management.DeleteLibrary; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.DeleteLibrary; @@ -67,6 +64,11 @@ public class DeleteLibraryEndpointTests : IClassFixture Assert.DoesNotContain(_apiFactory.ApiClientStub.DeleteEndpointsCalled, endpoint => endpoint == $"libraries/{libraryId}"); } + /// + /// Builds the delete request for the library identified by . + /// + /// The Id of the library to delete. + /// The configured delete request. private static HttpRequestMessage CreateDeleteRequest(Guid libraryId) { HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/libraries/manage/api-item/{libraryId}") diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs index 16917b88..22913584 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointTests.cs @@ -1,15 +1,13 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SaveLibrary; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Management.SaveLibrary; @@ -21,6 +19,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Managemen public class SaveLibraryEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly LibraryDtoFixture _libraryDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -37,7 +36,7 @@ public class SaveLibraryEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); // Act HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest); @@ -53,7 +52,7 @@ public class SaveLibraryEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); - HttpRequestMessage saveRequest = CreateSaveRequest(new LibraryDto { Title = "New Books Library", LibraryType = "Book" }); + HttpRequestMessage saveRequest = CreateSaveRequest(_libraryDtoFixture.Create(title: "New Books Library", libraryType: "Book")); saveRequest.Headers.Remove("RequestVerificationToken"); saveRequest.Headers.Add("RequestVerificationToken", "invalid-antiforgery-token"); @@ -70,8 +69,9 @@ public class SaveLibraryEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - LibraryDto request = new() { Title = "'; DROP TABLE Libraries--", LibraryType = "Book" }; - _apiFactory.ApiClientStub.RegisterPostResponse("libraries", new LibraryDto { Id = Guid.NewGuid(), Title = request.Title, LibraryType = request.LibraryType }); + LibraryDto request = _libraryDtoFixture.Create(title: "'; DROP TABLE Libraries--", libraryType: "Book"); + request.Id = null; + _apiFactory.ApiClientStub.RegisterPostResponse("libraries", _libraryDtoFixture.Create(id: Guid.NewGuid(), title: request.Title, libraryType: request.LibraryType)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage saveRequest = CreateSaveRequest(request); saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); @@ -86,6 +86,11 @@ public class SaveLibraryEndpointTests : IClassFixture Assert.DoesNotContain("Exception", content); } + /// + /// Builds the save request that sends the given to the library save endpoint. + /// + /// The library data to send. + /// The configured save request. private static HttpRequestMessage CreateSaveRequest(LibraryDto request) { HttpRequestMessage saveRequest = new(HttpMethod.Post, "/en-us/libraries/manage/api-item") diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs index a08a013b..392ac0b6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -1,15 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Core.Endpoints.Plugins.GetPlugins; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugins; @@ -21,6 +18,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.GetPlugin public class GetPluginsEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -55,7 +53,7 @@ public class GetPluginsEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); _apiFactory.ApiClientStub.RegisterGetException("plugins", new ApiException( - new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" }, + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginNotFound"), HttpStatusCode.NotFound)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/admin/manage-plugins/api-get-plugins"); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs index 6f6f6933..a3003933 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/InstallPlugin/InstallPluginEndpointTests.cs @@ -1,16 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Core.Endpoints.Plugins.InstallPlugin; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPlugin; @@ -22,6 +19,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.InstallPl public class InstallPluginEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -101,7 +99,7 @@ public class InstallPluginEndpointTests : IClassFixture // Arrange _apiFactory.ApiClientStub.Reset(); _apiFactory.ApiClientStub.RegisterPostException("plugins", new ApiException( - new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginArchiveNotReadable" }, + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginArchiveNotReadable"), HttpStatusCode.Forbidden)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage installRequest = new(HttpMethod.Post, "/en-us/admin/manage-plugins/api-install-plugin") diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index a0b6b2e9..868af133 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -1,18 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Requests.Plugins; using Lumina.Presentation.Web.Core.Endpoints.Plugins.UpdatePluginSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; @@ -24,6 +21,7 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Plugins.UpdatePlu public class UpdatePluginSettingsEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); /// @@ -89,7 +87,7 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); string endpoint = $"plugins/{request.PluginId}/settings"; _apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException( - new ProblemDetailsDto { Title = "General.Failure", Detail = "PluginNotFound" }, + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "PluginNotFound"), HttpStatusCode.NotFound)); AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/admin/manage-plugins/api-update-plugin-settings") diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index 4b186aa1..253f76ed 100644 --- a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -1,18 +1,16 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Requests.UsersManagement; using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Lumina.Presentation.Web.SecurityTests.Common.Setup; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.Authentication.Login; @@ -24,6 +22,8 @@ namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.UsersManagement.A public class LoginEndpointTests : IClassFixture { private readonly LuminaWebFactory _apiFactory; + private readonly LoginRequestFixture _loginRequestFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -44,10 +44,10 @@ public class LoginEndpointTests : IClassFixture { // Arrange _apiFactory.ApiClientStub.Reset(); - _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(new ProblemDetailsDto { Title = "General.Failure", Detail = "InvalidUsernameOrPassword" }, HttpStatusCode.Forbidden, "auth/login")); + _apiFactory.ApiClientStub.RegisterPostException("auth/login", new ApiException(_problemDetailsDtoFixture.Create(title: "General.Failure", detail: "InvalidUsernameOrPassword"), HttpStatusCode.Forbidden, "auth/login")); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: maliciousUsername, Password: "Abcd123$"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: maliciousUsername, password: "Abcd123$"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -71,7 +71,7 @@ public class LoginEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -96,7 +96,7 @@ public class LoginEndpointTests : IClassFixture _apiFactory.ApiClientStub.Reset(); HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); - HttpRequestMessage loginRequest = CreateLoginRequest(new LoginRequest(Username: "testuser", Password: "TestPass123!"), antiforgeryToken); + HttpRequestMessage loginRequest = CreateLoginRequest(_loginRequestFixture.Create(username: "testuser", password: "TestPass123!"), antiforgeryToken); // Act HttpResponseMessage response = await client.SendAsync(loginRequest); @@ -113,6 +113,12 @@ public class LoginEndpointTests : IClassFixture Assert.Contains("samesite=strict", tokenCookie, StringComparison.OrdinalIgnoreCase); } + /// + /// Builds the login request that sends the given to the login endpoint. + /// + /// The login request to send. + /// The antiforgery token to include in the request. + /// The configured login request. private static HttpRequestMessage CreateLoginRequest(LoginRequest request, string antiforgeryToken) { HttpRequestMessage loginRequest = new(HttpMethod.Post, "/en-us/auth/api-login") diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/PermissionEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/PermissionEntityMappingTests.cs index 6188de93..67b28faf 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/PermissionEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/PermissionEntityMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; @@ -17,15 +18,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class PermissionEntityMappingTests { + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly() { // Arrange - PermissionEntity entity = new() - { - Id = Guid.NewGuid(), - PermissionName = AuthorizationPermission.CanViewUsers - }; + PermissionEntity entity = _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers); // Act PermissionResponse result = entity.ToResponse(); @@ -44,11 +43,7 @@ public class PermissionEntityMappingTests public void ToResponse_WhenMappingDifferentPermissions_ShouldMapCorrectly(AuthorizationPermission permission) { // Arrange - PermissionEntity entity = new() - { - Id = Guid.NewGuid(), - PermissionName = permission - }; + PermissionEntity entity = _permissionEntityFixture.Create(permissionName: permission); // Act PermissionResponse result = entity.ToResponse(); @@ -65,9 +60,9 @@ public class PermissionEntityMappingTests // Arrange List entities = [ - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers }, - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanDeleteUsers }, - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanRegisterUsers } + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanRegisterUsers) ]; // Act @@ -101,11 +96,7 @@ public class PermissionEntityMappingTests public void ToResponse_WhenMappingDifferentIds_ShouldMapCorrectly(string idString) { // Arrange - PermissionEntity entity = new() - { - Id = Guid.Parse(idString), - PermissionName = AuthorizationPermission.CanViewUsers - }; + PermissionEntity entity = _permissionEntityFixture.Create(id: Guid.Parse(idString), permissionName: AuthorizationPermission.CanViewUsers); // Act PermissionResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/RoleEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/RoleEntityMappingTests.cs index 81170df2..5fff1925 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/RoleEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/RoleEntityMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; @@ -17,15 +18,15 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class RoleEntityMappingTests { + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly() { // Arrange - RoleEntity entity = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin" - }; + RoleEntity entity = _roleEntityFixture.Create(roleName: "Admin"); // Act RoleResponse result = entity.ToResponse(); @@ -41,36 +42,18 @@ public class RoleEntityMappingTests { // Arrange Guid roleId = Guid.NewGuid(); - RoleEntity role = new() - { - Id = roleId, - RoleName = "Admin" - }; + RoleEntity role = _roleEntityFixture.Create(id: roleId, roleName: "Admin"); role.RolePermissions = [ - new() - { - PermissionId = Guid.NewGuid(), - RoleId = roleId, - Role = role, - Permission = new() - { - Id = Guid.NewGuid(), - PermissionName = AuthorizationPermission.CanViewUsers - } - }, - new() - { - PermissionId = Guid.NewGuid(), - RoleId = roleId, - Role = role, - Permission = new() - { - Id = Guid.NewGuid(), - PermissionName = AuthorizationPermission.CanDeleteUsers - } - } + _rolePermissionEntityFixture.Create( + roleId: roleId, + role: role, + permission: _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)), + _rolePermissionEntityFixture.Create( + roleId: roleId, + role: role, + permission: _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers)) ]; // Act @@ -89,9 +72,9 @@ public class RoleEntityMappingTests // Arrange List entities = [ - new() { Id = Guid.NewGuid(), RoleName = "Admin" }, - new() { Id = Guid.NewGuid(), RoleName = "User" }, - new() { Id = Guid.NewGuid(), RoleName = "Guest" } + _roleEntityFixture.Create(roleName: "Admin"), + _roleEntityFixture.Create(roleName: "User"), + _roleEntityFixture.Create(roleName: "Guest") ]; // Act @@ -100,7 +83,7 @@ public class RoleEntityMappingTests // Assert Assert.NotNull(results); Assert.Equal(3, results.Count()); - List resultList = results.ToList(); + List resultList = [.. results]; for (int i = 0; i < entities.Count; i++) { Assert.Equal(entities[i].Id, resultList[i].Id); @@ -129,11 +112,7 @@ public class RoleEntityMappingTests public void ToResponse_WhenMappingDifferentRoleNames_ShouldMapCorrectly(string roleName) { // Arrange - RoleEntity entity = new() - { - Id = Guid.NewGuid(), - RoleName = roleName - }; + RoleEntity entity = _roleEntityFixture.Create(roleName: roleName); // Act RoleResponse result = entity.ToResponse(); @@ -151,11 +130,7 @@ public class RoleEntityMappingTests public void ToResponse_WhenMappingDifferentIds_ShouldMapCorrectly(string idString) { // Arrange - RoleEntity entity = new() - { - Id = Guid.Parse(idString), - RoleName = "Admin" - }; + RoleEntity entity = _roleEntityFixture.Create(id: Guid.Parse(idString), roleName: "Admin"); // Act RoleResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs index fa5743e8..8a544cc0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Authorization/UserAuthorizationEntityMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.Mapping.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using System; @@ -16,16 +17,15 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Authorization; [ExcludeFromCodeCoverage] public class UserAuthorizationEntityMappingTests { + private readonly UserAuthorizationEntityFixture _userAuthorizationEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidEntity_ShouldMapCorrectly() { // Arrange - UserAuthorizationEntity entity = new() - { - UserId = Guid.NewGuid(), - Role = "Admin", - Permissions = new HashSet { AuthorizationPermission.CanViewUsers } - }; + UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create( + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers }); // Act AuthorizationResponse result = entity.ToResponse(); @@ -41,12 +41,9 @@ public class UserAuthorizationEntityMappingTests public void ToResponse_WhenMappingEntityWithEmptyCollections_ShouldMapCorrectly() { // Arrange - UserAuthorizationEntity entity = new() - { - UserId = Guid.NewGuid(), - Role = string.Empty, - Permissions = new HashSet() - }; + UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create( + role: string.Empty, + permissions: new HashSet()); // Act AuthorizationResponse result = entity.ToResponse(); @@ -62,17 +59,14 @@ public class UserAuthorizationEntityMappingTests public void ToResponse_WhenMappingEntityWithMultipleRolesAndPermissions_ShouldMapCorrectly() { // Arrange - UserAuthorizationEntity entity = new() - { - UserId = Guid.NewGuid(), - Role = "Admin", - Permissions = new HashSet + UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create( + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers, AuthorizationPermission.CanRegisterUsers - } - }; + }); // Act AuthorizationResponse result = entity.ToResponse(); @@ -91,12 +85,10 @@ public class UserAuthorizationEntityMappingTests public void ToResponse_WhenMappingDifferentUserIds_ShouldMapCorrectly(string userIdString) { // Arrange - UserAuthorizationEntity entity = new() - { - UserId = Guid.Parse(userIdString), - Role = "Admin", - Permissions = new HashSet { AuthorizationPermission.CanViewUsers } - }; + UserAuthorizationEntity entity = _userAuthorizationEntityFixture.Create( + userId: Guid.Parse(userIdString), + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers }); // Act AuthorizationResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs index 36f3fa80..1501d085 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreDtoMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; @@ -16,11 +17,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class GenreDtoMappingTests { + private readonly GenreDtoFixture _genreDtoFixture = new(); + [Fact] public void ToDomainEntity_WhenMappingValidGenreDto_ShouldMapCorrectly() { // Arrange - GenreDto genreDto = new("Rock"); + GenreDto genreDto = _genreDtoFixture.Create(name: "Rock"); // Act Result result = genreDto.ToDomainEntity(); @@ -39,7 +42,7 @@ public class GenreDtoMappingTests public void ToDomainEntity_WhenMappingDifferentValidGenreDtos_ShouldMapCorrectly(string name) { // Arrange - GenreDto genreDto = new(name); + GenreDto genreDto = _genreDtoFixture.Create(name: name); // Act Result result = genreDto.ToDomainEntity(); @@ -57,7 +60,7 @@ public class GenreDtoMappingTests public void ToDomainEntity_WhenMappingInvalidGenreDto_ShouldReturnError(string? invalidName) { // Arrange - GenreDto genreDto = new(invalidName); + GenreDto genreDto = _genreDtoFixture.Create(name: invalidName, includeName: invalidName is not null); // Act Result result = genreDto.ToDomainEntity(); @@ -72,10 +75,10 @@ public class GenreDtoMappingTests // Arrange List genreDtos = [ - new GenreDto("Rock"), - new GenreDto("Jazz"), - new GenreDto("Classical"), - new GenreDto("Pop") + _genreDtoFixture.Create(name: "Rock"), + _genreDtoFixture.Create(name: "Jazz"), + _genreDtoFixture.Create(name: "Classical"), + _genreDtoFixture.Create(name: "Pop") ]; // Act @@ -99,10 +102,10 @@ public class GenreDtoMappingTests // Arrange List genreDtos = [ - new GenreDto("Rock"), - new GenreDto(""), - new GenreDto("Jazz"), - new GenreDto(" ") + _genreDtoFixture.Create(name: "Rock"), + _genreDtoFixture.Create(name: ""), + _genreDtoFixture.Create(name: "Jazz"), + _genreDtoFixture.Create(name: " ") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs index 37e7f560..898bd666 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreEntityMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -18,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class GenreEntityMappingTests { + private readonly GenreEntityFixture _genreEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidGenreEntity_ShouldMapCorrectly() { // Arrange - GenreEntity entity = new("Fiction"); + GenreEntity entity = _genreEntityFixture.Create(name: "Fiction"); // Act GenreDto result = entity.ToResponse(); @@ -40,7 +43,7 @@ public class GenreEntityMappingTests public void ToResponse_WhenMappingDifferentValidGenreEntities_ShouldMapCorrectly(string name) { // Arrange - GenreEntity entity = new(name); + GenreEntity entity = _genreEntityFixture.Create(name: name); // Act GenreDto result = entity.ToResponse(); @@ -57,7 +60,7 @@ public class GenreEntityMappingTests public void ToResponse_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) { // Arrange - GenreEntity entity = new(invalidName); + GenreEntity entity = _genreEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act GenreDto result = entity.ToResponse(); @@ -70,7 +73,7 @@ public class GenreEntityMappingTests public void ToDomainEntity_WhenMappingValidGenreEntity_ShouldMapCorrectly() { // Arrange - GenreEntity entity = new("Fiction"); + GenreEntity entity = _genreEntityFixture.Create(name: "Fiction"); // Act Result result = entity.ToDomainEntity(); @@ -88,7 +91,7 @@ public class GenreEntityMappingTests public void ToDomainEntity_WhenMappingInvalidGenreEntity_ShouldMapToDefault(string? invalidName) { // Arrange - GenreEntity entity = new(invalidName); + GenreEntity entity = _genreEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act Result result = entity.ToDomainEntity(); @@ -104,10 +107,10 @@ public class GenreEntityMappingTests // Arrange List entities = [ - new GenreEntity("Fiction"), - new GenreEntity("Mystery"), - new GenreEntity("Romance"), - new GenreEntity("Thriller") + _genreEntityFixture.Create(name: "Fiction"), + _genreEntityFixture.Create(name: "Mystery"), + _genreEntityFixture.Create(name: "Romance"), + _genreEntityFixture.Create(name: "Thriller") ]; // Act @@ -131,10 +134,10 @@ public class GenreEntityMappingTests // Arrange List entities = [ - new GenreEntity("Fiction"), - new GenreEntity("Mystery"), - new GenreEntity("Romance"), - new GenreEntity("Thriller") + _genreEntityFixture.Create(name: "Fiction"), + _genreEntityFixture.Create(name: "Mystery"), + _genreEntityFixture.Create(name: "Romance"), + _genreEntityFixture.Create(name: "Thriller") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs index c2c4de9d..22ca3c9c 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagDtoMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using System.Collections.Generic; @@ -16,11 +17,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class TagDtoMappingTests { + private readonly TagDtoFixture _tagDtoFixture = new(); + [Fact] public void ToDomainEntity_WhenMappingValidTagDto_ShouldMapCorrectly() { // Arrange - TagDto tagDto = new("indie"); + TagDto tagDto = _tagDtoFixture.Create(name: "indie"); // Act Result result = tagDto.ToDomainEntity(); @@ -40,7 +43,7 @@ public class TagDtoMappingTests public void ToDomainEntity_WhenMappingDifferentValidTagDtos_ShouldMapCorrectly(string name) { // Arrange - TagDto tagDto = new(name); + TagDto tagDto = _tagDtoFixture.Create(name: name); // Act Result result = tagDto.ToDomainEntity(); @@ -58,7 +61,7 @@ public class TagDtoMappingTests public void ToDomainEntity_WhenMappingInvalidTagDto_ShouldReturnError(string? invalidName) { // Arrange - TagDto tagDto = new(invalidName); + TagDto tagDto = _tagDtoFixture.Create(name: invalidName, includeName: invalidName is not null); // Act Result result = tagDto.ToDomainEntity(); @@ -73,10 +76,10 @@ public class TagDtoMappingTests // Arrange List tagDtos = [ - new TagDto("indie"), - new TagDto("electronic"), - new TagDto("instrumental"), - new TagDto("live") + _tagDtoFixture.Create(name: "indie"), + _tagDtoFixture.Create(name: "electronic"), + _tagDtoFixture.Create(name: "instrumental"), + _tagDtoFixture.Create(name: "live") ]; // Act @@ -100,10 +103,10 @@ public class TagDtoMappingTests // Arrange List tagDtos = [ - new TagDto("indie"), - new TagDto(""), - new TagDto("electronic"), - new TagDto(" ") + _tagDtoFixture.Create(name: "indie"), + _tagDtoFixture.Create(name: ""), + _tagDtoFixture.Create(name: "electronic"), + _tagDtoFixture.Create(name: " ") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs index a731b2bd..49ff084f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagEntityMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Contracts.DTO.Common; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -18,11 +19,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class TagEntityMappingTests { + private readonly TagEntityFixture _tagEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidTagEntity_ShouldMapCorrectly() { // Arrange - TagEntity entity = new("Fantasy"); + TagEntity entity = _tagEntityFixture.Create(name: "Fantasy"); // Act TagDto result = entity.ToResponse(); @@ -40,7 +43,7 @@ public class TagEntityMappingTests public void ToResponse_WhenMappingDifferentValidTagEntities_ShouldMapCorrectly(string name) { // Arrange - TagEntity entity = new(name); + TagEntity entity = _tagEntityFixture.Create(name: name); // Act TagDto result = entity.ToResponse(); @@ -57,7 +60,7 @@ public class TagEntityMappingTests public void ToResponse_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) { // Arrange - TagEntity entity = new(invalidName); + TagEntity entity = _tagEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act TagDto result = entity.ToResponse(); @@ -70,7 +73,7 @@ public class TagEntityMappingTests public void ToDomainEntity_WhenMappingValidTagEntity_ShouldMapCorrectly() { // Arrange - TagEntity entity = new("Fantasy"); + TagEntity entity = _tagEntityFixture.Create(name: "Fantasy"); // Act Result result = entity.ToDomainEntity(); @@ -88,7 +91,7 @@ public class TagEntityMappingTests public void ToDomainEntity_WhenMappingInvalidTagEntity_ShouldMapToDefault(string? invalidName) { // Arrange - TagEntity entity = new(invalidName); + TagEntity entity = _tagEntityFixture.Create(name: invalidName, includeName: invalidName is not null); // Act Result result = entity.ToDomainEntity(); @@ -104,10 +107,10 @@ public class TagEntityMappingTests // Arrange List entities = [ - new TagEntity("Fantasy"), - new TagEntity("Young Adult"), - new TagEntity("Historical"), - new TagEntity("Coming of Age") + _tagEntityFixture.Create(name: "Fantasy"), + _tagEntityFixture.Create(name: "Young Adult"), + _tagEntityFixture.Create(name: "Historical"), + _tagEntityFixture.Create(name: "Coming of Age") ]; // Act @@ -131,10 +134,10 @@ public class TagEntityMappingTests // Arrange List entities = [ - new TagEntity("Fantasy"), - new TagEntity("Young Adult"), - new TagEntity("Historical"), - new TagEntity("Coming of Age") + _tagEntityFixture.Create(name: "Fantasy"), + _tagEntityFixture.Create(name: "Young Adult"), + _tagEntityFixture.Create(name: "Historical"), + _tagEntityFixture.Create(name: "Coming of Age") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs index 53f28f53..87d15376 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; @@ -19,6 +19,9 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class AddBookRequestMappingTests { private readonly AddBookRequestFixture _requestFixture = new(); + private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new(); + private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new(); + private readonly MediaContributorRoleDtoFixture _mediaContributorRoleDtoFixture = new(); [Fact] public void ToCommand_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly() @@ -54,36 +57,12 @@ public class AddBookRequestMappingTests public void ToCommand_WhenMappingMinimalRequest_ShouldMapCorrectly() { // Arrange - AddBookRequest request = new( - LibraryId: Guid.NewGuid(), - Path: "/books/test.epub", - Metadata: new WrittenContentMetadataDto( - Title: "Test Book", - OriginalTitle: null, - Description: null, - ReleaseInfo: null, - Genres: null, - Tags: null, - Language: null, - OriginalLanguage: null, - Publisher: null, - PageCount: null), - Format: null, - Edition: null, - VolumeNumber: null, - Series: null, - ASIN: null, - GoodreadsId: null, - LCCN: null, - OCLCNumber: null, - OpenLibraryId: null, - LibraryThingId: null, - GoogleBooksId: null, - BarnesAndNobleId: null, - AppleBooksId: null, - ISBNs: null, - Contributors: null, - Ratings: null); + AddBookRequest request = _requestFixture.Create( + libraryId: Guid.NewGuid(), + path: "/books/test.epub", + metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), + includeOptionalProperties: false + ); // Act AddBookCommand result = request.ToCommand(); @@ -113,42 +92,21 @@ public class AddBookRequestMappingTests public void ToCommand_WhenMappingRequestWithCollections_ShouldMapCollectionsCorrectly() { // Arrange - AddBookRequest request = new( - LibraryId: Guid.NewGuid(), - Path: "/books/test.epub", - Metadata: new WrittenContentMetadataDto( - Title: "Test Book", - OriginalTitle: null, - Description: null, - ReleaseInfo: null, - Genres: null, - Tags: null, - Language: null, - OriginalLanguage: null, - Publisher: null, - PageCount: null), - Format: null, - Edition: null, - VolumeNumber: null, - Series: null, - ASIN: null, - GoodreadsId: null, - LCCN: null, - OCLCNumber: null, - OpenLibraryId: null, - LibraryThingId: null, - GoogleBooksId: null, - BarnesAndNobleId: null, - AppleBooksId: null, - ISBNs: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], - Contributors: + AddBookRequest request = _requestFixture.Create( + libraryId: Guid.NewGuid(), + path: "/books/test.epub", + metadata: _writtenContentMetadataDtoFixture.Create(title: "Test Book"), + isbns: [new("978-0-123456-78-9", IsbnFormat.Isbn13)], + contributors: [ new( - new MediaContributorNameDto("John Doe", "John Smith Doe"), - new MediaContributorRoleDto("Author", "Writing") + _mediaContributorNameDtoFixture.Create(displayName: "John Doe", legalName: "John Smith Doe"), + _mediaContributorRoleDtoFixture.Create(name: "Author", category: "Writing") ) ], - Ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)]); + ratings: [new(4.5m, 5m, BookRatingSource.Goodreads, 1000)], + includeOptionalProperties: false + ); // Act AddBookCommand result = request.ToCommand(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs index c74035c2..9847245b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMappingTests.cs @@ -4,7 +4,8 @@ using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Primitives; @@ -23,6 +24,9 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class BookEntityMappingTests { private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); [Fact] public void ToDomainEntity_WhenMappingValidBookEntity_ShouldMapCorrectly() @@ -297,12 +301,12 @@ public class BookEntityMappingTests Assert.Equal(bookEntity.GoogleBooksId, result.GoogleBooksId); Assert.Equal(bookEntity.BarnesAndNobleId, result.BarnesAndNobleId); Assert.Equal(bookEntity.AppleBooksId, result.AppleBooksId); - Assert.Equal(bookEntity.ISBNs.Select(i => new IsbnDto(i.Value, i.Format)), result.ISBNs); - Assert.Equal(bookEntity.Ratings.Select(r => new BookRatingDto( - r.Value, - r.MaxValue, - r.Source, - r.VoteCount + Assert.Equal(bookEntity.ISBNs.Select(i => _isbnDtoFixture.Create(value: i.Value, format: i.Format)), result.ISBNs); + Assert.Equal(bookEntity.Ratings.Select(r => _bookRatingDtoFixture.Create( + value: r.Value, + maxValue: r.MaxValue, + source: r.Source, + voteCount: r.VoteCount )), result.Ratings); Assert.Equal(bookEntity.CreatedOnUtc, result.CreatedOnUtc); Assert.Equal(bookEntity.UpdatedOnUtc, result.UpdatedOnUtc); @@ -343,21 +347,19 @@ public class BookEntityMappingTests { // Arrange List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBookEntities = new() - { - Data = bookEntities, - CurrentPage = 1, - PerPage = 10, - Count = 2, - NumberOfPages = 1 - }; + PaginatedResultDto paginatedBookEntities = _paginatedResultDtoFixture.Create( + data: bookEntities, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); // Act PaginatedResponse result = paginatedBookEntities.ToResponses(); // Assert Assert.NotNull(result); - Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count()); + Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count); Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage); Assert.Equal(paginatedBookEntities.PerPage, result.PerPage); Assert.Equal(paginatedBookEntities.Count, result.Count); @@ -406,7 +408,7 @@ public class BookEntityMappingTests // Assert Assert.NotNull(results); - Assert.Equal(bookEntities.Count, results.Count()); + Assert.Equal(bookEntities.Count, results.Count); } [Fact] @@ -414,21 +416,19 @@ public class BookEntityMappingTests { // Arrange List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBookEntities = new() - { - Data = bookEntities, - CurrentPage = 1, - PerPage = 10, - Count = 2, - NumberOfPages = 1 - }; + PaginatedResultDto paginatedBookEntities = _paginatedResultDtoFixture.Create( + data: bookEntities, + currentPage: 1, + perPage: 10, + count: 2, + numberOfPages: 1); // Act PaginatedResponse result = paginatedBookEntities.ToLiteResponses(); // Assert Assert.NotNull(result); - Assert.Equal(paginatedBookEntities.Data.Count(), result.Data.Count()); + Assert.Equal(paginatedBookEntities.Data.Count, result.Data.Count); Assert.Equal(paginatedBookEntities.CurrentPage, result.CurrentPage); Assert.Equal(paginatedBookEntities.PerPage, result.PerPage); Assert.Equal(paginatedBookEntities.Count, result.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs index 7cbff3fa..634bebee 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMappingTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; @@ -21,6 +21,7 @@ public class BookMetadataDtoMappingTests { private readonly BookFixture _bookFixture = new(); private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); [Fact] public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched() @@ -59,7 +60,7 @@ public class BookMetadataDtoMappingTests title: "The Fellowship of the Ring", goodreadsId: "3") with { - Genres = [new GenreDto("")] + Genres = [_genreDtoFixture.Create(name: "")] }; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs index 9fb56684..37c28ee3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnEntityMappingTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; @@ -19,11 +20,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten [ExcludeFromCodeCoverage] public class IsbnEntityMappingTests { + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidIsbnEntity_ShouldMapCorrectly() { // Arrange - IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10); + IsbnEntity entity = _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10); // Act IsbnDto result = entity.ToResponse(); @@ -40,7 +43,7 @@ public class IsbnEntityMappingTests public void ToResponse_WhenMappingDifferentValidIsbnEntities_ShouldMapCorrectly(string value, IsbnFormat format) { // Arrange - IsbnEntity entity = new(value, format); + IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format); // Act IsbnDto result = entity.ToResponse(); @@ -58,7 +61,7 @@ public class IsbnEntityMappingTests public void ToResponse_WhenMappingInvalidIsbnEntity_ShouldPreserveValues(string? value, IsbnFormat? format) { // Arrange - IsbnEntity entity = new(value, format); + IsbnEntity entity = _isbnEntityFixture.Create(value: value, format: format, includeValue: value is not null); // Act IsbnDto result = entity.ToResponse(); @@ -72,7 +75,7 @@ public class IsbnEntityMappingTests public void ToDomainEntity_WhenMappingValidIsbnEntity_ShouldMapCorrectly() { // Arrange - IsbnEntity entity = new("0-7475-3269-9", IsbnFormat.Isbn10); + IsbnEntity entity = _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10); // Act Result result = entity.ToDomainEntity(); @@ -91,7 +94,7 @@ public class IsbnEntityMappingTests public void ToDomainEntity_WhenMappingInvalidIsbnEntity_ShouldReturnError(string? invalidValue) { // Arrange - IsbnEntity entity = new(invalidValue, null); + IsbnEntity entity = _isbnEntityFixture.Create(value: invalidValue, includeValue: invalidValue is not null); // Act Result result = entity.ToDomainEntity(); @@ -106,8 +109,8 @@ public class IsbnEntityMappingTests // Arrange List entities = [ - new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10), - new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13) + _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10), + _isbnEntityFixture.Create(value: "978-0-7475-3269-9", format: IsbnFormat.Isbn13) ]; // Act @@ -132,8 +135,8 @@ public class IsbnEntityMappingTests // Arrange List entities = [ - new IsbnEntity("0-7475-3269-9", IsbnFormat.Isbn10), - new IsbnEntity("978-0-7475-3269-9", IsbnFormat.Isbn13) + _isbnEntityFixture.Create(value: "0-7475-3269-9", format: IsbnFormat.Isbn10), + _isbnEntityFixture.Create(value: "978-0-7475-3269-9", format: IsbnFormat.Isbn13) ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs index 1b398857..ef7c73ef 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UserManagement/Users/UserMappingTests.cs @@ -4,10 +4,11 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; using Lumina.Application.Common.Mapping.UsersManagement.Users; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; -using System; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; #endregion @@ -21,6 +22,8 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; public class UserMappingTests { private readonly UserFixture _userFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); [Fact] public void ToRepositoryEntity_WhenMappingValidUser_ShouldOnlyUpdateUsername() @@ -28,19 +31,7 @@ public class UserMappingTests // Arrange User domainEntity = _userFixture.Create(username: "newusername"); - UserEntity repositoryEntity = new() - { - Id = Guid.NewGuid(), - Username = "oldusername", - Password = "hashedpassword", - TotpSecret = "totpsecret", - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - UpdatedOnUtc = null - }; + UserEntity repositoryEntity = _userEntityFixture.Create(username: "oldusername", password: "hashedpassword"); // Act UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); @@ -73,18 +64,7 @@ public class UserMappingTests // Arrange User domainEntity = _userFixture.Create(username: newUsername); - UserEntity repositoryEntity = new() - { - Id = Guid.NewGuid(), - Username = "oldusername", - Password = "hashedpassword", - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - UpdatedOnUtc = null - }; + UserEntity repositoryEntity = _userEntityFixture.Create(username: "oldusername", password: "hashedpassword"); // Act UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); @@ -102,44 +82,14 @@ public class UserMappingTests List libraries = [ - new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "Library 1", - LibraryType = LibraryType.Book, - ContentLocations = [], - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - }, - new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "Library 2", - LibraryType = LibraryType.Movie, - ContentLocations = [], - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - } + _libraryEntityFixture.Create(title: "Library 1", libraryType: LibraryType.Book, contentLocations: []), + _libraryEntityFixture.Create(title: "Library 2", libraryType: LibraryType.Movie, contentLocations: []) ]; - UserEntity repositoryEntity = new() - { - Id = Guid.NewGuid(), - Username = "oldusername", - Password = "hashedpassword", - Libraries = libraries, - UserPermissions = [], - UserRole = null, - CreatedBy = Guid.NewGuid(), - CreatedOnUtc = DateTime.UtcNow, - UpdatedOnUtc = null - }; + UserEntity repositoryEntity = _userEntityFixture.Create( + username: "oldusername", + password: "hashedpassword", + libraries: libraries); // Act UserEntity result = domainEntity.ToRepositoryEntity(repositoryEntity); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs index aebf70e9..f43abf85 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandlerTests.cs @@ -6,6 +6,8 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Core.Admin.Authorization.Permissions.Queries.GetPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; @@ -32,6 +34,8 @@ public class GetPermissionsQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly GetPermissionsQueryHandler _sut; private readonly Guid _userId; + private readonly GetPermissionsQueryFixture _getPermissionsQueryFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -57,11 +61,11 @@ public class GetPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnPermissions() { // Arrange - GetPermissionsQuery query = new(); + GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); IEnumerable permissions = [ - new PermissionEntity { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers }, - new PermissionEntity { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanDeleteUsers } + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers) ]; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -83,7 +87,7 @@ public class GetPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnNotAuthorizedError() { // Arrange - GetPermissionsQuery query = new(); + GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(false); @@ -102,7 +106,7 @@ public class GetPermissionsQueryHandlerTests public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() { // Arrange - GetPermissionsQuery query = new(); + GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -119,7 +123,7 @@ public class GetPermissionsQueryHandlerTests public async Task HandleAsync_WhenGetAllPermissionsReturnsError_ShouldReturnError() { // Arrange - GetPermissionsQuery query = new(); + GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve permissions"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -141,10 +145,10 @@ public class GetPermissionsQueryHandlerTests public async Task HandleAsync_WhenCancellationRequested_ShouldStillCompleteOperation() { // Arrange - GetPermissionsQuery query = new(); + GetPermissionsQuery query = _getPermissionsQueryFixture.Create(); IEnumerable permissions = [ - new PermissionEntity { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers } + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers) ]; CancellationToken cancellationToken = new(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs index 9e85875c..aadc14c4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandlerTests.cs @@ -7,12 +7,14 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.AddRole; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -33,6 +35,9 @@ public class AddRoleCommandHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly AddRoleCommandHandler _sut; private readonly AddRoleCommandFixture _addRoleCommandFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); private readonly Guid _userId; /// @@ -163,22 +168,12 @@ public class AddRoleCommandHandlerTests // Arrange AddRoleCommand command = _addRoleCommandFixture.Create(); Guid roleId = Guid.NewGuid(); - RoleEntity role = new() - { - Id = roleId, - RoleName = command.RoleName, - RolePermissions = [.. command.Permissions.Select(p => new RolePermissionEntity - { - RoleId = roleId, - PermissionId = p, - Role = null!, - Permission = new() - { - Id = p, - PermissionName = AuthorizationPermission.CanViewUsers - } - })] - }; + List rolePermissions = [.. command.Permissions.Select(permissionId => + _rolePermissionEntityFixture.Create( + roleId: roleId, + permissionId: permissionId, + permission: _permissionEntityFixture.Create(id: permissionId, permissionName: AuthorizationPermission.CanViewUsers)))]; + RoleEntity role = _roleEntityFixture.Create(id: roleId, roleName: command.RoleName, includeRolePermissions: true, rolePermissions: rolePermissions); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs index cd17b6f7..5976f727 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.DeleteRole; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -30,6 +31,7 @@ public class DeleteRoleCommandHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly DeleteRoleCommandHandler _sut; private readonly DeleteRoleCommandFixture _deleteRoleCommandFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly Guid _userId; /// @@ -115,7 +117,7 @@ public class DeleteRoleCommandHandlerTests { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); - RoleEntity adminRole = new() { Id = command.RoleId, RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(id: command.RoleId, roleName: "Admin"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -157,7 +159,7 @@ public class DeleteRoleCommandHandlerTests { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); - RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" }; + RoleEntity role = _roleEntityFixture.Create(id: command.RoleId, roleName: "TestRole"); Error error = Error.Failure("Database.Error", "Failed to delete role"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -181,7 +183,7 @@ public class DeleteRoleCommandHandlerTests { // Arrange DeleteRoleCommand command = _deleteRoleCommandFixture.Create(); - RoleEntity role = new() { Id = command.RoleId, RoleName = "TestRole" }; + RoleEntity role = _roleEntityFixture.Create(id: command.RoleId, roleName: "TestRole"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs index 3771c17d..25e4bc67 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandlerTests.cs @@ -7,12 +7,14 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Commands.UpdateRole; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; using NSubstitute; using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; @@ -33,6 +35,9 @@ public class UpdateRoleCommandHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly UpdateRoleCommandHandler _sut; private readonly UpdateRoleCommandFixture _updateRoleCommandFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); private readonly Guid _userId; /// @@ -162,22 +167,12 @@ public class UpdateRoleCommandHandlerTests { // Arrange UpdateRoleCommand command = _updateRoleCommandFixture.Create(); - RoleEntity role = new() - { - Id = command.RoleId, - RoleName = command.RoleName, - RolePermissions = [.. command.Permissions.Select(p => new RolePermissionEntity - { - RoleId = command.RoleId, - PermissionId = p, - Role = null!, - Permission = new() - { - Id = p, - PermissionName = AuthorizationPermission.CanViewUsers - } - })] - }; + List rolePermissions = [.. command.Permissions.Select(permissionId => + _rolePermissionEntityFixture.Create( + roleId: command.RoleId, + permissionId: permissionId, + permission: _permissionEntityFixture.Create(id: permissionId, permissionName: AuthorizationPermission.CanViewUsers)))]; + RoleEntity role = _roleEntityFixture.Create(id: command.RoleId, roleName: command.RoleName, includeRolePermissions: true, rolePermissions: rolePermissions); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs index bc9a3781..2692d0bc 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -32,6 +33,9 @@ public class GetRolePermissionsQueryHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly GetRolePermissionsQueryHandler _sut; private readonly GetRolePermissionsQueryFixture _getRolePermissionsQueryFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); private readonly Guid _userId; /// @@ -136,25 +140,16 @@ public class GetRolePermissionsQueryHandlerTests { // Arrange GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create(); - RoleEntity role = new() - { - Id = query.RoleId, - RoleName = "TestRole", - RolePermissions = + RoleEntity role = _roleEntityFixture.Create( + id: query.RoleId, + roleName: "TestRole", + rolePermissions: [ - new() - { - RoleId = query.RoleId, - PermissionId = Guid.NewGuid(), - Role = null!, - Permission = new() - { - Id = Guid.NewGuid(), - PermissionName = AuthorizationPermission.CanViewUsers - } - } - ] - }; + _rolePermissionEntityFixture.Create( + roleId: query.RoleId, + permission: _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)) + ], + includeRolePermissions: true); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs index 66a8f107..ddec5b2f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Core.Admin.Authorization.Roles.Queries.GetRoles; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -31,6 +32,7 @@ public class GetRolesQueryHandlerTests private readonly IRoleRepository _mockRoleRepository; private readonly GetRolesQueryHandler _sut; private readonly GetRolesQueryFixture _getRolesQueryFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly Guid _userId; /// @@ -114,8 +116,8 @@ public class GetRolesQueryHandlerTests GetRolesQuery query = _getRolesQueryFixture.Create(); IEnumerable roles = [ - new RoleEntity { Id = Guid.NewGuid(), RoleName = "Admin" }, - new RoleEntity { Id = Guid.NewGuid(), RoleName = "User" } + _roleEntityFixture.Create(roleName: "Admin"), + _roleEntityFixture.Create(roleName: "User") ]; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs index 1089192a..d3a5fdf3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Paths/Queries/GetPathParent/GetPathParentQueryHandlerTests.cs @@ -4,6 +4,7 @@ using AutoFixture.AutoNSubstitute; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathParent; using Lumina.Application.Fixtures.Core.FileSystemManagement.Paths.Queries.GetPathParent; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -30,6 +31,7 @@ public class GetPathParentQueryHandlerTests private readonly GetPathParentQueryHandler _sut; private readonly PathSegmentFixture _pathSegmentFixture = new(); private readonly GetPathParentQueryFixture _getPathParentQueryFixture = new(); + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); public GetPathParentQueryHandlerTests() { @@ -50,7 +52,7 @@ public class GetPathParentQueryHandlerTests IEnumerable pathSegments = _pathSegmentFixture.CreateMany(); // Create PathSegmentResponses based on the PathSegments - IEnumerable pathSegmentResponses = pathSegments.Select(segment => new PathSegmentResponse(segment.Name)); + IEnumerable pathSegmentResponses = pathSegments.Select(segment => _pathSegmentResponseFixture.Create(path: segment.Name)); _mockPathService.GoUpOneLevel(query.Path!) .Returns(Result.From(pathSegments)); @@ -60,7 +62,7 @@ public class GetPathParentQueryHandlerTests // Assert Assert.False(result.IsFailure); - Assert.IsAssignableFrom>(result.Value); + Assert.IsType>(result.Value, exactMatch: false); Assert.Equal(pathSegmentResponses, result.Value); _mockPathService.Received(1).GoUpOneLevel(query.Path!); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs index 1432c22e..7771223e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Maintenance/ApplicationSetup/Queries/CheckInitialization/CheckInitializationQueryHandlerTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -25,6 +26,7 @@ public class CheckInitializationQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IUserRepository _mockUserRepository; private readonly CheckInitializationQueryHandler _sut; + private readonly CheckInitializationQueryFixture _checkInitializationQueryFixture = new(); private readonly UserEntityFixture _userEntityFixture = new(); /// @@ -49,7 +51,7 @@ public class CheckInitializationQueryHandlerTests .Returns(Result.From(users.AsEnumerable())); // Act - InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsInitialized); @@ -64,7 +66,7 @@ public class CheckInitializationQueryHandlerTests .Returns(Result.From(Enumerable.Empty())); // Act - InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); @@ -80,7 +82,7 @@ public class CheckInitializationQueryHandlerTests .Returns(error); // Act - InitializationResponse result = await _sut.HandleAsync(new CheckInitializationQuery(), CancellationToken.None); + InitializationResponse result = await _sut.HandleAsync(_checkInitializationQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsInitialized); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs index 20333317..cd47937e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs @@ -7,7 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Domain.Common.Events; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -15,7 +15,6 @@ 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; @@ -35,6 +34,7 @@ public class CancelLibrariesScanCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly CancelLibrariesScanCommandHandler _sut; + private readonly CancelLibrariesScanCommandFixture _cancelLibrariesScanCommandFixture = new(); private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); private readonly Guid _userId; @@ -72,7 +72,7 @@ public class CancelLibrariesScanCommandHandlerTests _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -96,7 +96,7 @@ public class CancelLibrariesScanCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -111,7 +111,7 @@ public class CancelLibrariesScanCommandHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -128,7 +128,7 @@ public class CancelLibrariesScanCommandHandlerTests .Returns(Error.Failure(description: "Failed to get running scans")); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -146,7 +146,7 @@ public class CancelLibrariesScanCommandHandlerTests .Returns(Error.Failure(description: "Failed to update library scan")); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -161,7 +161,7 @@ public class CancelLibrariesScanCommandHandlerTests _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); // Act - Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + Result result = await _sut.HandleAsync(_cancelLibrariesScanCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs index a402d079..9fe9a29d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs @@ -7,8 +7,8 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.ScanLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; using NSubstitute; @@ -37,6 +37,7 @@ public class ScanLibrariesCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly ScanLibrariesCommandHandler _sut; + private readonly ScanLibrariesCommandFixture _scanLibrariesCommandFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); private readonly Guid _userId; @@ -79,7 +80,7 @@ public class ScanLibrariesCommandHandlerTests _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -105,7 +106,7 @@ public class ScanLibrariesCommandHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -122,7 +123,7 @@ public class ScanLibrariesCommandHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -139,7 +140,7 @@ public class ScanLibrariesCommandHandlerTests .Returns(Error.Failure(description: "Failed to get libraries")); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -161,7 +162,7 @@ public class ScanLibrariesCommandHandlerTests .Returns(Result.From>([runningScan])); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -181,7 +182,7 @@ public class ScanLibrariesCommandHandlerTests .Returns(Error.Failure(description: "Failed to insert library scan")); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -198,7 +199,7 @@ public class ScanLibrariesCommandHandlerTests .Returns(Error.Failure(description: "Failed to get past month scans")); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -214,7 +215,7 @@ public class ScanLibrariesCommandHandlerTests _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); // Act - Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_scanLibrariesCommandFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs index 940b7ed9..93451f92 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -30,6 +31,7 @@ public class LibraryDeletedDomainEventHandlerTests private readonly IPathService _mockPathService; private readonly LibraryDeletedDomainEventHandler _sut; private readonly LibraryFixture _libraryFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -41,11 +43,10 @@ public class LibraryDeletedDomainEventHandlerTests _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); _mockPathService = Substitute.For(); - MediaSettingsDto mediaSettings = new() - { - RootDirectory = "Media", - LibrariesDirectory = "Libraries" - }; + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create( + rootDirectory: "Media", + librariesDirectory: "Libraries", + booksDirectory: "Books"); IOptions mediaSettingsOptions = Substitute.For>(); mediaSettingsOptions.Value.Returns(mediaSettings); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index e53e7369..a7c49d0f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Application.Core.MediaLibrary.Management.Events; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; @@ -44,6 +45,7 @@ public class LibrarySavedDomainEventHandlerTests private readonly LibraryFixture _libraryFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -62,11 +64,10 @@ public class LibrarySavedDomainEventHandlerTests _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); _mockPathService = Substitute.For(); - MediaSettingsDto mediaSettings = new() - { - RootDirectory = "Media", - LibrariesDirectory = "Libraries" - }; + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create( + rootDirectory: "Media", + librariesDirectory: "Libraries", + booksDirectory: "Books"); IOptions mediaSettingsOptions = Substitute.For>(); mediaSettingsOptions.Value.Returns(mediaSettings); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs index 8f4e33c7..03ef4f4e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -5,8 +5,8 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Core.MediaLibrary.Management.Events; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Exceptions; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; @@ -14,13 +14,12 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library 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 DomainErrors = Lumina.Domain.Common.Errors.Errors; using NSubstitute; using System; -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.Events; @@ -52,7 +51,7 @@ public class LibraryScanQueuedDomainEventHandlerTests _mockDomainEventsQueue = Substitute.For(); // default stubs: the scanning service starts the scan successfully - _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Result.Success); _sut = new LibraryScanQueuedDomainEventHandler(_mockMediaLibraryScanningService, _mockDomainEventsQueue, _mockUnitOfWork); @@ -74,7 +73,6 @@ public class LibraryScanQueuedDomainEventHandlerTests await _mockMediaLibraryScanningService.Received(1).StartScanAsync( Arg.Is(libraryScan => libraryScan.Id.Value == scan.Id), scan.Library.LibraryType, - scan.Library.DownloadMetadataFromWeb, Arg.Any()); } @@ -93,7 +91,7 @@ public class LibraryScanQueuedDomainEventHandlerTests // Assert Assert.Equal(error, exception.EventualConsistencyError); - await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] @@ -110,7 +108,7 @@ public class LibraryScanQueuedDomainEventHandlerTests // Assert Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); - await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] @@ -122,7 +120,7 @@ public class LibraryScanQueuedDomainEventHandlerTests _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) .Returns(Result.From(scan)); Error error = Error.Failure(description: "Failed to start scan"); - _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(error); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs index 07363bed..a1ed34ef 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs @@ -7,13 +7,13 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -31,6 +31,7 @@ public class GetEnabledLibrariesQueryHandlerTests private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly GetEnabledLibrariesQueryHandler _sut; + private readonly GetEnabledLibrariesQueryFixture _getEnabledLibrariesQueryFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly Guid _userId; @@ -65,7 +66,7 @@ public class GetEnabledLibrariesQueryHandlerTests _mockLibraryRepository.GetAllEnabledAsync(Arg.Any()).Returns(Result.From>(libraries)); // Act - Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getEnabledLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -88,7 +89,7 @@ public class GetEnabledLibrariesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act - Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getEnabledLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -103,7 +104,7 @@ public class GetEnabledLibrariesQueryHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getEnabledLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -119,7 +120,7 @@ public class GetEnabledLibrariesQueryHandlerTests .Returns(Error.Failure(description: "Failed to get enabled libraries")); // Act - Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getEnabledLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs index 622e3880..e69ccda4 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs @@ -7,13 +7,13 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraries; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -31,6 +31,7 @@ public class GetLibrariesQueryHandlerTests private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly GetLibrariesQueryHandler _sut; + private readonly GetLibrariesQueryFixture _getLibrariesQueryFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly Guid _userId; @@ -65,7 +66,7 @@ public class GetLibrariesQueryHandlerTests _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); // Act - Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -88,7 +89,7 @@ public class GetLibrariesQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act - Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -103,7 +104,7 @@ public class GetLibrariesQueryHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -119,7 +120,7 @@ public class GetLibrariesQueryHandlerTests .Returns(Error.Failure(description: "Failed to get libraries")); // Act - Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + Result result = await _sut.HandleAsync(_getLibrariesQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs index ea8c6d7e..45bf6b28 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibrary/GetLibraryQueryHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibrary; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Errors; @@ -14,7 +15,6 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -38,6 +38,7 @@ public class GetLibraryQueryHandlerTests private readonly GetLibraryQueryHandler _sut; private readonly Guid _userId; private readonly GetLibraryQueryFixture _getLibraryQueryFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -57,17 +58,7 @@ public class GetLibraryQueryHandlerTests _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From((LibraryEntity?)new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = _userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = _userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - })); + .Returns(Result.From((LibraryEntity?)_libraryEntityFixture.Create(userId: _userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []))); _mockValidator.Validate(Arg.Any()).Returns([]); _sut = new GetLibraryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs index c5d3c2d8..fea2650e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; @@ -37,6 +38,7 @@ public class GetRunningLibraryScansQueryHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; private readonly GetRunningLibraryScansQueryHandler _sut; + private readonly GetRunningLibraryScansQueryFixture _getRunningLibraryScansQueryFixture = new(); private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new(); private readonly UserIdFixture _userIdFixture = new(); @@ -80,7 +82,7 @@ public class GetRunningLibraryScansQueryHandlerTests _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); // Act - Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -100,7 +102,7 @@ public class GetRunningLibraryScansQueryHandlerTests _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); // Act - Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -114,7 +116,7 @@ public class GetRunningLibraryScansQueryHandlerTests _mockCurrentUserService.UserId.Returns((Guid?)null); // Act - Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -130,7 +132,7 @@ public class GetRunningLibraryScansQueryHandlerTests .Returns(Error.Failure(description: "Failed to get running scans")); // Act - Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -146,7 +148,7 @@ public class GetRunningLibraryScansQueryHandlerTests .Returns(Error.Failure(description: "Failed to get scan progress")); // Act - Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getRunningLibraryScansQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs index fbe1d2f8..734dab1f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandHandlerTests.cs @@ -8,8 +8,8 @@ using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Application.Fixtures.Common.Setup; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; -using Lumina.Contracts.DTO.Common; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; @@ -34,6 +34,12 @@ public class AddBookCommandHandlerTests private readonly IBookRepository _mockBookRepository; private readonly AddBookCommandHandler _sut; private readonly AddBookCommandFixture _commandBookFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -98,7 +104,7 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { ISBNs = [new IsbnDto("invalid", IsbnFormat.Isbn13)] }; + bookCommand = bookCommand with { ISBNs = [_isbnDtoFixture.Create(value: "invalid", format: IsbnFormat.Isbn13)] }; // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -115,7 +121,7 @@ public class AddBookCommandHandlerTests { // Arrange AddBookCommand bookCommand = _commandBookFixture.Create(); - bookCommand = bookCommand with { Ratings = [new BookRatingDto(-1, 5, null, null)] }; + bookCommand = bookCommand with { Ratings = [_bookRatingDtoFixture.Create(value: -1, maxValue: 5, includeOptionalProperties: false)] }; // Act Result result = await _sut.HandleAsync(bookCommand, CancellationToken.None); @@ -136,7 +142,7 @@ public class AddBookCommandHandlerTests { Metadata = bookCommand.Metadata! with { - Genres = [new GenreDto("")] + Genres = [_genreDtoFixture.Create(name: "")] } }; @@ -159,7 +165,7 @@ public class AddBookCommandHandlerTests { Metadata = bookCommand.Metadata! with { - Tags = [new TagDto("")] + Tags = [_tagDtoFixture.Create(name: "")] } }; @@ -182,14 +188,9 @@ public class AddBookCommandHandlerTests { Metadata = bookCommand.Metadata! with { - ReleaseInfo = new ReleaseInfoDto( - OriginalReleaseDate: new DateOnly(2025, 1, 1), - ReReleaseDate: new DateOnly(2024, 1, 1), - OriginalReleaseYear: null, - ReReleaseYear: null, - ReleaseCountry: null, - ReleaseVersion: null - ) + ReleaseInfo = _releaseInfoDtoFixture.Create( + originalReleaseDate: new DateOnly(2025, 1, 1), + reReleaseDate: new DateOnly(2024, 1, 1)) } }; @@ -212,7 +213,7 @@ public class AddBookCommandHandlerTests { Metadata = bookCommand.Metadata! with { - Language = new LanguageInfoDto("", "English", null) + Language = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English") } }; @@ -235,7 +236,7 @@ public class AddBookCommandHandlerTests { Metadata = bookCommand.Metadata! with { - OriginalLanguage = new LanguageInfoDto("", "English", null) + OriginalLanguage = _languageInfoDtoFixture.Create(languageCode: "", languageName: "English") } }; diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs index 731697a1..37421e16 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidatorTests.cs @@ -1881,4 +1881,18 @@ public class AddBookCommandValidatorTests // Assert result.ShouldNotHaveValidationError(Errors.Metadata.RatingVoteCountMustBePositive); } + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + AddBookCommand bookCommand = _commandBookFixture.Create(); + bookCommand = bookCommand with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(bookCommand); + + // Assert + result.ShouldHaveValidationError(Errors.WrittenContent.BookLibraryCannotBeNull); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs index 3235a3c7..33dbaa4d 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooks/GetBooksQueryHandlerTests.cs @@ -2,12 +2,15 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -18,12 +21,9 @@ 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; -using Lumina.Application.Common.DTO.Filtering; -using Lumina.Application.Common.DTO.Pagination; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; @@ -43,6 +43,7 @@ public class GetBooksQueryHandlerTests private readonly Guid _userId; private readonly BookEntityFixture _bookEntityFixture = new(); private readonly GetBooksQueryFixture _getBooksQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -73,14 +74,7 @@ public class GetBooksQueryHandlerTests GetBooksQuery query = _getBooksQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBooks = new() - { - Data = bookEntities, - CurrentPage = 1, - PerPage = 10, - Count = 2, - NumberOfPages = 1 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -106,14 +100,7 @@ public class GetBooksQueryHandlerTests { // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -157,14 +144,7 @@ public class GetBooksQueryHandlerTests // Arrange GetBooksQuery query = _getBooksQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -190,20 +170,8 @@ public class GetBooksQueryHandlerTests public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksQuery query = new( - PaginationData: null, - Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() }, - SortBy: null, - SortOrder: SortOrder.Ascending - ); - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + GetBooksQuery query = _getBooksQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs index 80ca4f0d..ad7669c0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Queries/GetBooksLite/GetBooksLiteQueryHandlerTests.cs @@ -2,12 +2,15 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Common.DTO.Pagination; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -18,12 +21,9 @@ 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; -using Lumina.Application.Common.DTO.Filtering; -using Lumina.Application.Common.DTO.Pagination; #endregion namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; @@ -43,6 +43,7 @@ public class GetBooksLiteQueryHandlerTests private readonly Guid _userId; private readonly BookEntityFixture _bookEntityFixture = new(); private readonly GetBooksLiteQueryFixture _getBooksLiteQueryFixture = new(); + private readonly PaginatedResultDtoFixture _paginatedResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -73,14 +74,7 @@ public class GetBooksLiteQueryHandlerTests GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; List bookEntities = _bookEntityFixture.CreateMany(2); - PaginatedResultDto paginatedBooks = new() - { - Data = bookEntities, - CurrentPage = 1, - PerPage = 10, - Count = 2, - NumberOfPages = 1 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: bookEntities, currentPage: 1, perPage: 10, count: 2, numberOfPages: 1); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -106,14 +100,7 @@ public class GetBooksLiteQueryHandlerTests { // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -157,14 +144,7 @@ public class GetBooksLiteQueryHandlerTests // Arrange GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), @@ -190,20 +170,8 @@ public class GetBooksLiteQueryHandlerTests public async Task HandleAsync_WhenQueryHasNoPaginationData_ShouldQueryRepositoryWithoutPagination() { // Arrange - GetBooksLiteQuery query = new( - PaginationData: null, - Filter: new LibraryFilterDto { LibraryId = Guid.NewGuid() }, - SortBy: null, - SortOrder: SortOrder.Ascending - ); - PaginatedResultDto paginatedBooks = new() - { - Data = [], - CurrentPage = 1, - PerPage = 10, - Count = 0, - NumberOfPages = 0 - }; + GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create(includePaginationData: false, libraryId: Guid.NewGuid(), sortOrder: SortOrder.Ascending); + PaginatedResultDto paginatedBooks = _paginatedResultDtoFixture.Create(data: [], currentPage: 1, perPage: 10, count: 0, numberOfPages: 0); _mockBookRepository.GetPaginatedAsync( Arg.Any(), Arg.Any(), diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs index 42feab39..45bd8263 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPlugins/GetPluginsQueryHandlerTests.cs @@ -4,13 +4,14 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Core.Plugins.Queries.GetPlugins; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPlugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; using NSubstitute; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPlugins; @@ -24,6 +25,8 @@ public class GetPluginsQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; private readonly GetPluginsQueryHandler _sut; + private readonly GetPluginsQueryFixture _getPluginsQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -40,12 +43,11 @@ public class GetPluginsQueryHandlerTests public async Task HandleAsync_WhenCalled_ShouldReturnAllDetectedPlugins() { // Arrange - PluginEntityFixture pluginFixture = new(); - List plugins = [pluginFixture.Create(), pluginFixture.Create()]; + List plugins = [_pluginEntityFixture.Create(), _pluginEntityFixture.Create()]; _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); // Act - Result> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -62,7 +64,7 @@ public class GetPluginsQueryHandlerTests .Returns(Error.Failure(description: "Failed to get plugins")); // Act - Result> result = await _sut.HandleAsync(new GetPluginsQuery(), CancellationToken.None); + Result> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs index 051aecfa..2958bb72 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeArchive/GetThemeArchiveQueryHandlerTests.cs @@ -2,18 +2,16 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Themes.Management.Queries.GetThemeArchive; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeArchive; using Lumina.Contracts.Responses.Themes; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading; @@ -35,6 +33,7 @@ public class GetThemeArchiveQueryHandlerTests private readonly GetThemeArchiveQueryHandler _sut; private readonly GetThemeArchiveQueryFixture _getThemeArchiveQueryFixture = new(); private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly ThemeArchiveDtoFixture _themeArchiveDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -136,7 +135,7 @@ public class GetThemeArchiveQueryHandlerTests _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeService.BuildArchiveAsync(theme.ThemeId, Arg.Any()) - .Returns(Result.From(new ThemeArchiveDto(bytes, fileName, contentType))); + .Returns(Result.From(_themeArchiveDtoFixture.Create(bytes: bytes, fileName: fileName, contentType: contentType))); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs index 073979b0..c3dfd888 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Themes/Management/Queries/GetThemeAsset/GetThemeAssetQueryHandlerTests.cs @@ -2,19 +2,17 @@ using Lumina.Application.Common.DataAccess.Entities.Themes; using Lumina.Application.Common.DataAccess.Repositories.Themes; using Lumina.Application.Common.DataAccess.UoW; -using Lumina.Application.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Themes.Management.Queries.GetThemeAsset; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Themes; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Themes; using Lumina.Application.Fixtures.Core.Themes.Management.Queries.GetThemeAsset; using Lumina.Contracts.Responses.Themes; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Themes; using NSubstitute; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading; @@ -36,6 +34,7 @@ public class GetThemeAssetQueryHandlerTests private readonly GetThemeAssetQueryHandler _sut; private readonly GetThemeAssetQueryFixture _getThemeAssetQueryFixture = new(); private readonly ThemeEntityFixture _themeEntityFixture = new(); + private readonly ThemeAssetDtoFixture _themeAssetDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -135,7 +134,7 @@ public class GetThemeAssetQueryHandlerTests _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) - .Returns(Result.From(new ThemeAssetDto(bytes, contentType))); + .Returns(Result.From(_themeAssetDtoFixture.Create(bytes: bytes, contentType: contentType))); // Act Result result = await _sut.HandleAsync(query, CancellationToken.None); @@ -203,7 +202,7 @@ public class GetThemeAssetQueryHandlerTests _mockThemeRepository.GetByThemeIdAsync(query.ThemeId!, Arg.Any()) .Returns(Result.From(theme)); _mockThemeService.GetAssetAsync(theme.ThemeId, query.AssetPath!, Arg.Any()) - .Returns(assetError, Result.From(new ThemeAssetDto(restoredBytes, contentType))); + .Returns(assetError, Result.From(_themeAssetDtoFixture.Create(bytes: restoredBytes, contentType: contentType))); _mockThemeService.RestoreBundledThemeAsync(theme.ThemeId, Arg.Any()) .Returns(Result.Success); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs index 639f1db5..0eec39ab 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Commands/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsCommandHandlerTests.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; using Lumina.Contracts.Responses.Authorization; @@ -40,7 +41,11 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests private readonly IPermissionRepository _mockPermissionRepository; private readonly UpdateUserRoleAndPermissionsCommandHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); private readonly UpdateUserRoleAndPermissionsCommandFixture _updateUserRoleAndPermissionsCommandFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); private readonly Guid _userId; /// @@ -150,28 +155,18 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); - RoleEntity adminRole = new() { RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); Guid userId = Guid.NewGuid(); + UserRoleEntity userRole = _userRoleEntityFixture.Create(userId: userId, role: adminRole); - UserEntity user = new() - { - Id = userId, - Username = "testAdmin", - Password = "hashedPassword", - Libraries = [], - UserPermissions = [], - UserRole = new UserRoleEntity - { - UserId = userId, - RoleId = Guid.NewGuid(), - User = null!, - Role = adminRole - }, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = userId - }; + UserEntity user = _userEntityFixture.Create( + id: userId, + username: "testAdmin", + password: "hashedPassword", + userRole: userRole, + includeUserRole: true); - RoleEntity newRole = new() { RoleName = "User" }; + RoleEntity newRole = _roleEntityFixture.Create(roleName: "User"); IEnumerable users = [user]; _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -197,9 +192,9 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); UserEntity user = _userEntityFixture.Create(); - RoleEntity role = new() { RoleName = "TestRole" }; - IEnumerable permissions = command.Permissions.Select(p => - new PermissionEntity { Id = p, PermissionName = AuthorizationPermission.CanViewUsers }); + RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole"); + IEnumerable permissions = command.Permissions.Select(permissionId => + _permissionEntityFixture.Create(id: permissionId, permissionName: AuthorizationPermission.CanViewUsers)); Error error = Error.Failure("Database.Error", "Failed to update user"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -227,30 +222,18 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); - UserEntity user = new() - { - Id = command.UserId, - Username = "testUser", - Password = "hashedPassword", - Libraries = [], - UserPermissions = [.. command.Permissions.Select((p, i) => new UserPermissionEntity - { - UserId = command.UserId, - PermissionId = p, - User = null!, - Permission = new PermissionEntity - { - Id = p, - PermissionName = (AuthorizationPermission)(i + 1) - } - })], - UserRole = null, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = command.UserId - }; - RoleEntity role = new() { RoleName = "TestRole" }; - IEnumerable permissions = command.Permissions.Select((p, i) => - new PermissionEntity { Id = p, PermissionName = (AuthorizationPermission)(i + 1) }); + UserEntity user = _userEntityFixture.Create(id: command.UserId, username: "testUser", password: "hashedPassword"); + + List userPermissions = [.. command.Permissions.Select((permissionId, index) => + _userPermissionEntityFixture.Create( + user: user, + permission: _permissionEntityFixture.Create(id: permissionId, permissionName: (AuthorizationPermission)(index + 1))))]; + foreach (UserPermissionEntity userPermission in userPermissions) + user.UserPermissions.Add(userPermission); + + RoleEntity role = _roleEntityFixture.Create(roleName: "TestRole"); + IEnumerable permissions = command.Permissions.Select((permissionId, index) => + _permissionEntityFixture.Create(id: permissionId, permissionName: (AuthorizationPermission)(index + 1))); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); @@ -279,23 +262,16 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); - UserEntity user = new() - { - Id = command.UserId, - Username = "testUser", - Password = "hashedPassword", - Libraries = [], - UserPermissions = [], - UserRole = new UserRoleEntity - { - UserId = command.UserId, - RoleId = Guid.NewGuid(), - User = null!, - Role = new RoleEntity { RoleName = "Admin" } - }, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = command.UserId - }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); + UserRoleEntity userRole = _userRoleEntityFixture.Create(userId: command.UserId, role: adminRole); + + UserEntity user = _userEntityFixture.Create( + id: command.UserId, + username: "testUser", + password: "hashedPassword", + userRole: userRole, + includeUserRole: true); + Error error = Error.Failure("Database.Error", "Failed to get users"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -303,7 +279,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) .Returns(user); _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) - .Returns(new RoleEntity { RoleName = "User" }); + .Returns(_roleEntityFixture.Create(roleName: "User")); _mockUserRepository.GetAllAsync(Arg.Any()) .Returns(error); @@ -320,17 +296,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests { // Arrange UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create(roleId: Guid.NewGuid()); - UserEntity user = new() - { - Id = command.UserId, - Username = "testUser", - Password = "hashedPassword", - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = command.UserId - }; + UserEntity user = _userEntityFixture.Create(id: command.UserId, username: "testUser", password: "hashedPassword"); Error error = Error.Failure("Database.Error", "Failed to get permissions"); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) @@ -338,7 +304,7 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests _mockUserRepository.GetByIdAsync(command.UserId, Arg.Any()) .Returns(user); _mockRoleRepository.GetByIdAsync(command.RoleId!.Value, Arg.Any()) - .Returns(new RoleEntity { RoleName = "User" }); + .Returns(_roleEntityFixture.Create(roleName: "User")); _mockPermissionRepository.GetByIdsAsync(command.Permissions, Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs index 7ae50f3f..8100d620 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserPermissions/GetUserPermissionsQueryHandlerTests.cs @@ -7,6 +7,8 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserPermissions; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -34,6 +36,9 @@ public class GetUserPermissionsQueryHandlerTests private readonly IUserRepository _mockUserRepository; private readonly GetUserPermissionsQueryHandler _sut; private readonly GetUserPermissionsQueryFixture _getUserPermissionsQueryFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); private readonly Guid _userId; /// @@ -138,26 +143,17 @@ public class GetUserPermissionsQueryHandlerTests { // Arrange GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create(); - UserEntity user = new() - { - Id = query.UserId!.Value, - Username = "testUser", - Password = "hashedPassword", - Libraries = [], - UserPermissions = + UserEntity user = _userEntityFixture.Create( + username: "testUser", + password: "hashedPassword", + id: query.UserId!.Value, + userPermissions: [ - new() - { - UserId = query.UserId!.Value, - PermissionId = Guid.NewGuid(), - User = null!, - Permission = new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers } - } + _userPermissionEntityFixture.Create( + _userEntityFixture.Create(id: query.UserId!.Value), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)) ], - UserRole = null, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = query.UserId!.Value - }; + includeUserPermissions: true); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs index 4eb87e9c..15e3cde3 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Authorization/Queries/GetUserRole/GetUserRoleQueryHandlerTests.cs @@ -7,6 +7,7 @@ using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Fixtures.Core.UsersManagement.Authorization.Queries.GetUserRole; using Lumina.Contracts.Responses.Authorization; @@ -32,6 +33,8 @@ public class GetUserRoleQueryHandlerTests private readonly IUserRepository _mockUserRepository; private readonly GetUserRoleQueryHandler _sut; private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); private readonly GetUserRoleQueryFixture _getUserRoleQueryFixture = new(); private readonly Guid _userId; @@ -157,23 +160,14 @@ public class GetUserRoleQueryHandlerTests { // Arrange GetUserRoleQuery query = _getUserRoleQueryFixture.Create(); - UserEntity user = new() - { - Id = query.UserId!.Value, - Username = "testUser", - Password = "hashedPassword", - Libraries = [], - UserPermissions = [], - UserRole = new() - { - UserId = query.UserId!.Value, - RoleId = Guid.NewGuid(), - User = null!, - Role = new() { Id = Guid.NewGuid(), RoleName = "TestRole" } - }, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = query.UserId!.Value - }; + UserEntity user = _userEntityFixture.Create( + username: "testUser", + password: "hashedPassword", + id: query.UserId!.Value, + userRole: _userRoleEntityFixture.Create( + userId: query.UserId!.Value, + role: _roleEntityFixture.Create(roleName: "TestRole")), + includeUserRole: true); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()) .Returns(true); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs index 63854886..80ba7f10 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaContributors; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; @@ -84,7 +83,7 @@ public class AddBookRequestTests AddBookRequest sut = _addBookRequestFixture.Create(); // Act - (Guid libraryId, string path, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, int? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; + (Guid libraryId, string path, WrittenContentMetadataDto? metadata, BookFormat? format, string? edition, float? volumeNumber, BookSeriesDto? series, string? asin, string? goodreadsId, string? lccn, string? oclcNumber, string? openLibraryId, string? libraryThingId, string? googleBooksId, string? barnesAndNobleId, string? appleBooksId, List? isbns, List? contributors, List? ratings) = sut; // Assert Assert.Equal(sut.LibraryId, libraryId); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs index bb8829ec..ad60760c 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs @@ -72,7 +72,7 @@ public class GetBooksLiteRequestTests GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); // Act - (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; + (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; // Assert Assert.Equal(sut.LibraryId, libraryId); @@ -80,7 +80,7 @@ public class GetBooksLiteRequestTests Assert.Equal(sut.PerPage, perPage); Assert.Equal(sut.SearchTerm, searchTerm); Assert.Equal(sut.FilterAlphaKey, filterAlphaKey); - Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); Assert.Equal(sut.SortBy, sortBy); Assert.Equal(sut.SortOrder, sortOrder); } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs index 61989f15..849c5353 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Authorization/RoleRepositoryTests.cs @@ -26,6 +26,8 @@ public class RoleRepositoryTests { private readonly LuminaDbContext _mockContext; private readonly RoleRepository _sut; + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly RolePermissionEntityFixture _rolePermissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -40,13 +42,7 @@ public class RoleRepositoryTests public async Task InsertAsync_WhenRoleDoesNotExist_ShouldAddRoleToContextAndReturnCreated() { // Arrange - RoleEntity role = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); // Act Result result = await _sut.InsertAsync(role, CancellationToken.None); @@ -65,24 +61,12 @@ public class RoleRepositoryTests public async Task InsertAsync_WhenRoleWithSameIdExists_ShouldReturnError() { // Arrange - RoleEntity existingRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin"); _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); - RoleEntity newRole = new() - { - Id = existingRole.Id, - RoleName = "SuperAdmin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity newRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: "SuperAdmin"); // Act Result result = await _sut.InsertAsync(newRole, CancellationToken.None); @@ -97,24 +81,12 @@ public class RoleRepositoryTests public async Task InsertAsync_WhenRoleWithSameNameExists_ShouldReturnError() { // Arrange - RoleEntity existingRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin"); _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); - RoleEntity newRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity newRole = _roleEntityFixture.Create(roleName: "Admin"); // Act Result result = await _sut.InsertAsync(newRole, CancellationToken.None); @@ -131,20 +103,8 @@ public class RoleRepositoryTests // Arrange List roles = [ - new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }, - new() - { - Id = Guid.NewGuid(), - RoleName = "User", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - } + _roleEntityFixture.Create(roleName: "Admin"), + _roleEntityFixture.Create(roleName: "User") ]; _mockContext.Roles.AddRange(roles); @@ -176,13 +136,7 @@ public class RoleRepositoryTests public async Task GetByNameAsync_WhenRoleExists_ShouldReturnRoleWithPermissions() { // Arrange - RoleEntity role = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity role = _roleEntityFixture.Create(roleName: "Admin"); _mockContext.Roles.Add(role); await _mockContext.SaveChangesAsync(); @@ -211,8 +165,7 @@ public class RoleRepositoryTests public async Task GetByIdAsync_WhenRoleExists_ShouldReturnRoleWithPermissions() { // Arrange - RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.Create(); + RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(); RoleEntity role = rolePermission.Role; _mockContext.Roles.Add(role); @@ -248,26 +201,14 @@ public class RoleRepositoryTests public async Task UpdateAsync_WhenRoleExists_ShouldUpdateRoleAndReturnUpdated() { // Arrange - RoleEntity existingRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin"); _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); - RoleEntity updatedRole = new() - { - Id = existingRole.Id, - RoleName = "SuperAdmin", - CreatedOnUtc = existingRole.CreatedOnUtc, - CreatedBy = existingRole.CreatedBy, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = Guid.NewGuid() - }; + RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: "SuperAdmin", createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc); + updatedRole.UpdatedOnUtc = DateTime.UtcNow; + updatedRole.UpdatedBy = Guid.NewGuid(); // Act Result result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); @@ -286,13 +227,7 @@ public class RoleRepositoryTests public async Task UpdateAsync_WhenRoleDoesNotExist_ShouldReturnError() { // Arrange - RoleEntity nonExistentRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity nonExistentRole = _roleEntityFixture.Create(roleName: "Admin"); // Act Result result = await _sut.UpdateAsync(nonExistentRole, CancellationToken.None); @@ -306,25 +241,17 @@ public class RoleRepositoryTests public async Task UpdateAsync_WhenRoleHasPermissions_ShouldUpdatePermissionsAndReturnUpdated() { // Arrange - RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.Create(); + RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(); RoleEntity existingRole = rolePermission.Role; existingRole.RolePermissions = [rolePermission]; _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); - RolePermissionEntity newRolePermission = rolePermissionFixture.Create(); - RoleEntity updatedRole = new() - { - Id = existingRole.Id, - RoleName = existingRole.RoleName, - RolePermissions = [newRolePermission], - CreatedOnUtc = existingRole.CreatedOnUtc, - CreatedBy = existingRole.CreatedBy, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = Guid.NewGuid() - }; + RolePermissionEntity newRolePermission = _rolePermissionEntityFixture.Create(); + RoleEntity updatedRole = _roleEntityFixture.Create(id: existingRole.Id, roleName: existingRole.RoleName, rolePermissions: [newRolePermission], includeRolePermissions: true, createdBy: existingRole.CreatedBy, createdOnUtc: existingRole.CreatedOnUtc); + updatedRole.UpdatedOnUtc = DateTime.UtcNow; + updatedRole.UpdatedBy = Guid.NewGuid(); // Act Result result = await _sut.UpdateAsync(updatedRole, CancellationToken.None); @@ -344,13 +271,7 @@ public class RoleRepositoryTests public async Task DeleteByIdAsync_WhenRoleExists_ShouldDeleteRoleAndReturnDeleted() { // Arrange - RoleEntity existingRole = new() - { - Id = Guid.NewGuid(), - RoleName = "Admin", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity existingRole = _roleEntityFixture.Create(roleName: "Admin"); _mockContext.Roles.Add(existingRole); await _mockContext.SaveChangesAsync(); @@ -386,8 +307,7 @@ public class RoleRepositoryTests public async Task DeleteByIdAsync_WhenRoleHasPermissions_ShouldDeleteRoleWithPermissions() { // Arrange - RolePermissionEntityFixture rolePermissionFixture = new(); - RolePermissionEntity rolePermission = rolePermissionFixture.Create(); + RolePermissionEntity rolePermission = _rolePermissionEntityFixture.Create(); RoleEntity existingRole = rolePermission.Role; existingRole.RolePermissions = [rolePermission]; diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs index 7a4bbb14..ca8aeb78 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs @@ -125,13 +125,7 @@ public class DirectoryScanFingerprintRepositoryTests : IDisposable await _context.SaveChangesAsync(); DateTime newLastWriteTimeUtc = DateTime.UtcNow.AddDays(1); - DirectoryScanFingerprintEntity updatedFingerprint = new() - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - Path = "/dir1", - LastWriteTimeUtc = newLastWriteTimeUtc - }; + DirectoryScanFingerprintEntity updatedFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: newLastWriteTimeUtc); // Act Result result = await _sut.UpsertRangeAsync([updatedFingerprint], CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs index 0ff25b41..0333e942 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -163,18 +163,12 @@ public class LibraryRepositoryTests _mockContext.Libraries.Add(library); await _mockContext.SaveChangesAsync(); - LibraryEntity updatedLibrary = new() - { - Id = library.Id, - UserId = library.UserId, - Title = "Updated Title", - LibraryType = library.LibraryType, - ContentLocations = [new LibraryContentLocationEntity { Path = "/new/path" }], - CreatedOnUtc = library.CreatedOnUtc, - CreatedBy = library.CreatedBy, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = library.UserId - }; + LibraryEntity updatedLibrary = _libraryEntityFixture.Create( + id: library.Id, + userId: library.UserId, + title: "Updated Title", + libraryType: library.LibraryType, + contentLocations: ["/new/path"]); // Act Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs index ebeb3f10..bd0ea81a 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -149,19 +149,9 @@ public class LibraryScanRepositoryTests _mockContext.LibraryScans.Add(libraryScan); await _mockContext.SaveChangesAsync(); - LibraryScanEntity updatedScan = new() - { - Id = libraryScan.Id, - LibraryId = libraryScan.LibraryId, - UserId = libraryScan.UserId, - Status = LibraryScanJobStatus.Completed, - Library = libraryScan.Library, - User = libraryScan.User, - CreatedOnUtc = libraryScan.CreatedOnUtc, - CreatedBy = libraryScan.CreatedBy, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = libraryScan.UserId - }; + LibraryScanEntity updatedScan = _libraryScanEntityFixture.Create(id: libraryScan.Id, libraryId: libraryScan.LibraryId, userId: libraryScan.UserId, status: LibraryScanJobStatus.Completed, libraryEntity: libraryScan.Library, createdOnUtc: libraryScan.CreatedOnUtc); + updatedScan.UpdatedOnUtc = DateTime.UtcNow; + updatedScan.UpdatedBy = libraryScan.UserId; // Act Result result = await _sut.UpdateAsync(updatedScan, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs index 7e0759cf..1fe8bf95 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs @@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; using Lumina.DataAccess.Core.Repositories.Libraries; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Primitives; @@ -39,6 +40,7 @@ public class LibraryScanStagingResultsRepositoryTests : IDisposable private readonly UserEntityFixture _userEntityFixture = new(); private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -235,8 +237,8 @@ public class LibraryScanStagingResultsRepositoryTests : IDisposable List hashedFiles = [ - new HashedFileSystemFileDto { Path = "/books/a.epub", Size = 10, Ticks = 100, CurrentHash = 999, OldHash = 0 }, - new HashedFileSystemFileDto { Path = "/books/b.epub", Size = 20, Ticks = 200, CurrentHash = 888, OldHash = 0 } + _hashedFileSystemFileDtoFixture.Create(path: "/books/a.epub", size: 10, ticks: 100, currentHash: 999, oldHash: 0), + _hashedFileSystemFileDtoFixture.Create(path: "/books/b.epub", size: 20, ticks: 200, currentHash: 888, oldHash: 0) ]; // Act diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs index 2595091e..8f754788 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserRepositoryTests.cs @@ -30,6 +30,9 @@ public class UserRepositoryTests private readonly UserRepository _sut; private readonly UserEntityFixture _userEntityFixture = new(); private readonly PermissionEntityFixture _permissionEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly UserRoleEntityFixture _userRoleEntityFixture = new(); + private readonly UserPermissionEntityFixture _userPermissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -143,20 +146,11 @@ public class UserRepositoryTests await _mockContext.SaveChangesAsync(); // Create updated user with same Id but different properties - UserEntity updatedUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, // Keep username as it's used for lookup - Password = "NewPassword123", - TempPassword = "TempPass456", - TotpSecret = "NewSecret", - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedBy = existingUser.Id, - CreatedOnUtc = existingUser.CreatedOnUtc, - UpdatedOnUtc = DateTime.UtcNow - }; + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword123"); + updatedUser.TempPassword = "TempPass456"; + updatedUser.TotpSecret = "NewSecret"; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; // Act Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); @@ -235,30 +229,13 @@ public class UserRepositoryTests _mockContext.Permissions.Add(newPermission); await _mockContext.SaveChangesAsync(); - UserEntity updatedUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = "NewPassword", - Libraries = [], - UserRole = null, - UserPermissions = - [ - new() - { - Id = Guid.NewGuid(), - UserId = existingUser.Id, - User = existingUser, - PermissionId = newPermission.Id, - Permission = newPermission, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = existingUser.Id - } - ], - CreatedBy = existingUser.CreatedBy, - CreatedOnUtc = existingUser.CreatedOnUtc, - UpdatedOnUtc = DateTime.UtcNow - }; + UserPermissionEntity newUserPermission = _userPermissionEntityFixture.Create(existingUser, newPermission); + newUserPermission.CreatedOnUtc = DateTime.UtcNow; + + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: "NewPassword", userPermissions: [newUserPermission], includeUserPermissions: true); + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; // Act Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); @@ -280,50 +257,24 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenUserHasExistingPermissions_ShouldRemoveOldPermissionsAndAddNew() { // Arrange - UserEntityFixture userFixture = new(); - PermissionEntityFixture permissionFixture = new(); - UserPermissionEntityFixture userPermissionFixture = new(); + UserEntity existingUser = _userEntityFixture.Create(); + PermissionEntity oldPermission = _permissionEntityFixture.Create(); + PermissionEntity newPermission = _permissionEntityFixture.Create(); - UserEntity existingUser = userFixture.Create(); - PermissionEntity oldPermission = permissionFixture.Create(); - PermissionEntity newPermission = permissionFixture.Create(); - - UserEntity userWithPermissions = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = existingUser.Password, - Libraries = existingUser.Libraries, - UserRole = null, - UserPermissions = - [ - userPermissionFixture.Create(existingUser, oldPermission) - ], - CreatedOnUtc = existingUser.CreatedOnUtc, - CreatedBy = existingUser.CreatedBy, - UpdatedOnUtc = existingUser.UpdatedOnUtc, - UpdatedBy = existingUser.UpdatedBy - }; + UserEntity userWithPermissions = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [_userPermissionEntityFixture.Create(existingUser, oldPermission)], includeUserPermissions: true); + userWithPermissions.CreatedOnUtc = existingUser.CreatedOnUtc; + userWithPermissions.CreatedBy = existingUser.CreatedBy; + userWithPermissions.UpdatedOnUtc = existingUser.UpdatedOnUtc; + userWithPermissions.UpdatedBy = existingUser.UpdatedBy; _mockContext.Users.Add(userWithPermissions); await _mockContext.SaveChangesAsync(); - UserEntity updatedUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = existingUser.Password, - Libraries = existingUser.Libraries, - UserRole = null, - UserPermissions = - [ - userPermissionFixture.Create(existingUser, newPermission) - ], - CreatedBy = existingUser.CreatedBy, - CreatedOnUtc = existingUser.CreatedOnUtc, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = existingUser.Id - }; + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userPermissions: [_userPermissionEntityFixture.Create(existingUser, newPermission)], includeUserPermissions: true); + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; + updatedUser.UpdatedBy = existingUser.Id; // Act Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); @@ -349,84 +300,40 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenUserRoleChanges_ShouldRemoveOldRoleAndAddNew() { // Arrange - RoleEntity oldRole = new() - { - Id = Guid.NewGuid(), - RoleName = "OldRole", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity oldRole = _roleEntityFixture.Create(roleName: "OldRole"); + oldRole.CreatedOnUtc = DateTime.UtcNow; + oldRole.CreatedBy = Guid.NewGuid(); - RoleEntity newRole = new() - { - Id = Guid.NewGuid(), - RoleName = "NewRole", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + RoleEntity newRole = _roleEntityFixture.Create(roleName: "NewRole"); + newRole.CreatedOnUtc = DateTime.UtcNow; + newRole.CreatedBy = Guid.NewGuid(); - UserEntity existingUser = new() - { - Id = Guid.NewGuid(), - Username = "TestUser", - Password = "TestPass", - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + UserEntity existingUser = _userEntityFixture.Create(username: "TestUser", password: "TestPass"); + existingUser.CreatedOnUtc = DateTime.UtcNow; + existingUser.CreatedBy = Guid.NewGuid(); - UserRoleEntity oldUserRole = new() - { - Id = Guid.NewGuid(), - UserId = existingUser.Id, - User = existingUser, - RoleId = oldRole.Id, - Role = oldRole, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + UserRoleEntity oldUserRole = _userRoleEntityFixture.Create(userId: existingUser.Id, user: existingUser, roleId: oldRole.Id, role: oldRole); + oldUserRole.CreatedOnUtc = DateTime.UtcNow; + oldUserRole.CreatedBy = Guid.NewGuid(); - existingUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = existingUser.Password, - Libraries = [], - UserRole = oldUserRole, - UserPermissions = [], - CreatedOnUtc = existingUser.CreatedOnUtc, - CreatedBy = existingUser.CreatedBy - }; + DateTime originalCreatedOnUtc = existingUser.CreatedOnUtc; + Guid originalCreatedBy = existingUser.CreatedBy; + existingUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userRole: oldUserRole, includeUserRole: true); + existingUser.CreatedOnUtc = originalCreatedOnUtc; + existingUser.CreatedBy = originalCreatedBy; _mockContext.Users.Add(existingUser); await _mockContext.SaveChangesAsync(); - UserRoleEntity newUserRole = new() - { - Id = Guid.NewGuid(), - UserId = existingUser.Id, - User = existingUser, - RoleId = newRole.Id, - Role = newRole, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = existingUser.Id - }; + UserRoleEntity newUserRole = _userRoleEntityFixture.Create(userId: existingUser.Id, user: existingUser, roleId: newRole.Id, role: newRole); + newUserRole.CreatedOnUtc = DateTime.UtcNow; + newUserRole.CreatedBy = existingUser.Id; - UserEntity updatedUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = existingUser.Password, - Libraries = [], - UserRole = newUserRole, - UserPermissions = [], - CreatedBy = existingUser.CreatedBy, - CreatedOnUtc = existingUser.CreatedOnUtc, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = existingUser.Id - }; + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password, userRole: newUserRole, includeUserRole: true); + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; + updatedUser.UpdatedBy = existingUser.Id; // Act Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); @@ -454,39 +361,20 @@ public class UserRepositoryTests public async Task UpdateAsync_WhenRemovingUserRole_ShouldRemoveRoleAndNotAddNew() { // Arrange - UserEntityFixture userFixture = new(); - UserRoleEntityFixture userRoleFixture = new(); + UserRoleEntity oldUserRole = _userRoleEntityFixture.Create(); - UserRoleEntity oldUserRole = userRoleFixture.Create(); - - UserEntity existingUser = new() - { - Id = Guid.NewGuid(), - Username = "TestUser", - Password = "TestPass", - Libraries = [], - UserRole = oldUserRole, - UserPermissions = [], - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid() - }; + UserEntity existingUser = _userEntityFixture.Create(username: "TestUser", password: "TestPass", userRole: oldUserRole, includeUserRole: true); + existingUser.CreatedOnUtc = DateTime.UtcNow; + existingUser.CreatedBy = Guid.NewGuid(); _mockContext.Users.Add(existingUser); await _mockContext.SaveChangesAsync(); - UserEntity updatedUser = new() - { - Id = existingUser.Id, - Username = existingUser.Username, - Password = existingUser.Password, - Libraries = [], - UserRole = null, - UserPermissions = [], - CreatedBy = existingUser.CreatedBy, - CreatedOnUtc = existingUser.CreatedOnUtc, - UpdatedOnUtc = DateTime.UtcNow, - UpdatedBy = existingUser.Id - }; + UserEntity updatedUser = _userEntityFixture.Create(id: existingUser.Id, username: existingUser.Username, password: existingUser.Password); + updatedUser.CreatedBy = existingUser.CreatedBy; + updatedUser.CreatedOnUtc = existingUser.CreatedOnUtc; + updatedUser.UpdatedOnUtc = DateTime.UtcNow; + updatedUser.UpdatedBy = existingUser.Id; // Act Result result = await _sut.UpdateAsync(updatedUser, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs index cdb0aca5..7c0a0164 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Users/UserSettingsRepositoryTests.cs @@ -119,7 +119,7 @@ public class UserSettingsRepositoryTests Assert.Equal(settings.UserId, result.Value.UserId); Assert.Equal(settings.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(settings.ItemsPerPage, result.Value.ItemsPerPage); - Assert.Equal(settings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(settings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] @@ -146,7 +146,7 @@ public class UserSettingsRepositoryTests userId: existingSettings.UserId, isPaginationEnabled: false, itemsPerPage: 12, - ignoreThePrefixForAlphaPicker: true); + shouldIgnoreThePrefixForAlphaPicker: true); // Act Result result = await _sut.UpdateAsync(updatedSettings, CancellationToken.None); @@ -160,7 +160,7 @@ public class UserSettingsRepositoryTests Assert.Equal(existingSettings.UserId, modifiedSettings.UserId); Assert.False(modifiedSettings.IsPaginationEnabled); Assert.Equal(12, modifiedSettings.ItemsPerPage); - Assert.True(modifiedSettings.IgnoreThePrefixForAlphaPicker); + Assert.True(modifiedSettings.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs index 6c96edc1..a9349aa8 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Seed/DataSeedServiceTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Authorization; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.DataAccess.Core.Seed; using Lumina.Domain.Common.Primitives; @@ -31,6 +32,9 @@ public class DataSeedServiceTests private readonly IPermissionRepository _mockPermissionRepository; private readonly DataSeedService _sut; private readonly DateTime _fixedUtcNow; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly RoleEntityFixture _roleEntityFixture = new(); + private readonly PermissionEntityFixture _permissionEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -226,12 +230,12 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); List permissions = [ - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers }, - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanDeleteUsers }, - new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanRegisterUsers } + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers), + _permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanRegisterUsers) ]; IRoleRepository mockRoleRepository = Substitute.For(); @@ -291,7 +295,7 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); Error expectedError = Error.Failure("Permissions.NotFound", "Failed to retrieve permissions"); IRoleRepository mockRoleRepository = Substitute.For(); @@ -318,8 +322,8 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; - List permissions = [new() { Id = Guid.NewGuid(), PermissionName = AuthorizationPermission.CanViewUsers }]; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); + List permissions = [_permissionEntityFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)]; Error expectedError = Error.Failure("RolePermission.InsertFailed", "Failed to insert role permission"); IRoleRepository mockRoleRepository = Substitute.For(); @@ -373,9 +377,8 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; - UserEntityFixture userFixture = new(); - UserEntity adminUser = userFixture.Create(); + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); + UserEntity adminUser = _userEntityFixture.Create(); // Use the adminUser.Id instead of the randomly generated userId userId = adminUser.Id; @@ -437,7 +440,7 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); IRoleRepository mockRoleRepository = Substitute.For(); IUserRepository mockUserRepository = Substitute.For(); @@ -463,8 +466,8 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; - UserEntity adminUser = new UserEntityFixture().Create(); + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); + UserEntity adminUser = _userEntityFixture.Create(); Error expectedError = Error.Failure("UserRole.InsertFailed", "Failed to insert user role"); @@ -519,7 +522,7 @@ public class DataSeedServiceTests { // Arrange Guid userId = Guid.NewGuid(); - RoleEntity adminRole = new() { Id = Guid.NewGuid(), RoleName = "Admin" }; + RoleEntity adminRole = _roleEntityFixture.Create(roleName: "Admin"); Error expectedError = Error.Failure("User.NotFound", "Failed to retrieve user"); IRoleRepository mockRoleRepository = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs index fd417778..46c95657 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs @@ -20,7 +20,6 @@ using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; @@ -72,7 +71,7 @@ public class MediaLibraryScanningServiceTests IMediaTypeScanner scanner = CreateScanner([job]); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -95,7 +94,7 @@ public class MediaLibraryScanningServiceTests LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -111,11 +110,11 @@ public class MediaLibraryScanningServiceTests // Arrange LibraryScan scan = _libraryScanFixture.Create(); IMediaTypeScanner scanner = Substitute.For(); - scanner.CreateScanJobsForLibrary(Arg.Any(), Arg.Any()).Returns(_ => throw new NotImplementedException()); + scanner.CreateScanJobsForLibrary(Arg.Any()).Returns(_ => throw new NotImplementedException()); _mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -135,7 +134,7 @@ public class MediaLibraryScanningServiceTests IMediaTypeScanner scanner = CreateScanner([firstRoot, secondRoot]); // Act - Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -180,14 +179,24 @@ public class MediaLibraryScanningServiceTests Assert.Equal(userId, leafJob.UserId); } + /// + /// Creates a mocked and registers it with the mocked scanner factory. + /// + /// The scan jobs the scanner returns when asked to create scan jobs for a library. + /// The created mocked scanner. private IMediaTypeScanner CreateScanner(List jobs) { IMediaTypeScanner scanner = Substitute.For(); - scanner.CreateScanJobsForLibrary(Arg.Any(), Arg.Any()).Returns(jobs); + scanner.CreateScanJobsForLibrary(Arg.Any()).Returns(jobs); _mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner); return scanner; } + /// + /// Creates a mocked scan job with the given children. + /// + /// The child scan jobs of the created job. + /// The created mocked scan job. private static IMediaLibraryScanJob CreateJob(List children) { IMediaLibraryScanJob job = Substitute.For(); @@ -195,6 +204,10 @@ public class MediaLibraryScanningServiceTests return job; } + /// + /// Counts and drains the scan jobs currently enqueued on the scan queue channel. + /// + /// The number of enqueued scan jobs. private int CountEnqueuedJobs() { int count = 0; diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs index dc1b200e..b100f5d6 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -42,33 +40,7 @@ public class BookLibraryTypeScannerTests } [Fact] - public void CreateScanJobsForLibrary_WhenDownloadMetadataFromWebIsFalse_ShouldCreateJobChainWithoutMetadataEnrichment() - { - // Arrange - LibraryId libraryId = _libraryIdFixture.Create(); - TestScanJob discoveryJob = CreateJob(); - TestScanJob diffJob = CreateJob(); - TestScanJob hashJob = CreateJob(); - TestScanJob saveJob = CreateJob(); - BookLibraryTypeScanner sut = new(_mockJobFactory); - - // Act - List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId, downloadMetadataFromWeb: false)]; - - // Assert - IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); - Assert.Same(discoveryJob, rootJob); - Assert.Contains(diffJob, discoveryJob.Children); - Assert.Contains(discoveryJob, diffJob.Parents); - Assert.Contains(hashJob, diffJob.Children); - Assert.Contains(diffJob, hashJob.Parents); - Assert.Contains(saveJob, hashJob.Children); - Assert.Contains(hashJob, saveJob.Parents); - _mockJobFactory.DidNotReceive().CreateJob(Arg.Any()); - } - - [Fact] - public void CreateScanJobsForLibrary_WhenDownloadMetadataFromWebIsTrue_ShouldCreateJobChainWithMetadataEnrichment() + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobChainWithMetadataEnrichment() { // Arrange LibraryId libraryId = _libraryIdFixture.Create(); @@ -80,12 +52,17 @@ public class BookLibraryTypeScannerTests BookLibraryTypeScanner sut = new(_mockJobFactory); // Act - List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId, downloadMetadataFromWeb: true)]; + List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId)]; // Assert IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); Assert.Same(discoveryJob, rootJob); + Assert.Contains(diffJob, discoveryJob.Children); + Assert.Contains(discoveryJob, diffJob.Parents); + Assert.Contains(hashJob, diffJob.Children); + Assert.Contains(diffJob, hashJob.Parents); Assert.Contains(saveJob, hashJob.Children); + Assert.Contains(hashJob, saveJob.Parents); Assert.Contains(enrichmentJob, saveJob.Children); Assert.Contains(saveJob, enrichmentJob.Parents); _mockJobFactory.Received(1).CreateJob(libraryId); @@ -100,16 +77,18 @@ public class BookLibraryTypeScannerTests CreateJob(); CreateJob(); CreateJob(); + CreateJob(); BookLibraryTypeScanner sut = new(_mockJobFactory); // Act - _ = sut.CreateScanJobsForLibrary(libraryId, downloadMetadataFromWeb: false).ToList(); + _ = sut.CreateScanJobsForLibrary(libraryId).ToList(); // Assert _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); _mockJobFactory.Received(1).CreateJob(libraryId); + _mockJobFactory.Received(1).CreateJob(libraryId); } private TestScanJob CreateJob() where TJob : class, IMediaLibraryScanJob diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index ddfd630d..50efc90a 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -3,11 +3,12 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Infrastructure.Common.Models.DTO.Plugins; -using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins; using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Plugins; using Lumina.Plugins.Contracts.Core.Plugins; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -40,6 +41,7 @@ public class PluginDetectionSyncJobTests private readonly IPluginManager _mockPluginManager; private readonly ILogger _mockLogger; private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture; + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -166,8 +168,8 @@ public class PluginDetectionSyncJobTests _mockPluginManager.GetPlugins().Returns([loadedPlugin]); _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Updated)); - PluginEntity loadedPluginRow = CreatePluginEntity(loadedPlugin.Id, loadedPlugin.Name, PluginLoadStatus.Loaded); - PluginEntity stalePluginRow = CreatePluginEntity(Guid.NewGuid(), "Stale Plugin", PluginLoadStatus.Loaded); + PluginEntity loadedPluginRow = _pluginEntityFixture.Create(id: loadedPlugin.Id, name: loadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); + PluginEntity stalePluginRow = _pluginEntityFixture.Create(name: "Stale Plugin", loadStatus: PluginLoadStatus.Loaded); _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Result.From((IEnumerable)[loadedPluginRow, stalePluginRow])); _mockPluginRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) @@ -194,7 +196,7 @@ public class PluginDetectionSyncJobTests PluginLoadErrorDto loadError = _pluginLoadErrorDtoFixture.Create( assemblyName: "MyPlugin", errorMessage: "Failed to load plugin assembly 'MyPlugin.dll': unexpected error"); - PluginEntity staleLoadedRow = CreatePluginEntity(previouslyLoadedPlugin.Id, previouslyLoadedPlugin.Name, PluginLoadStatus.Loaded); + PluginEntity staleLoadedRow = _pluginEntityFixture.Create(id: previouslyLoadedPlugin.Id, name: previouslyLoadedPlugin.Name, loadStatus: PluginLoadStatus.Loaded); _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Result.From((IEnumerable)[staleLoadedRow])); _mockPluginRepository.DeleteByIdAsync(previouslyLoadedPlugin.Id, Arg.Any()) @@ -254,29 +256,6 @@ public class PluginDetectionSyncJobTests return plugin; } - /// - /// Creates a stored plugin row with the provided identity. - /// - /// The Id of the plugin row. - /// The name of the plugin row. - /// The load status of the plugin row. - /// The created plugin entity. - private static PluginEntity CreatePluginEntity(Guid id, string name, PluginLoadStatus loadStatus) - { - return new PluginEntity - { - Id = id, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "Test plugin description", - LoadStatus = loadStatus, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedBy = default - }; - } - /// /// Derives the stable plugin Id expected for a failing plugin assembly, mirroring the detection job logic. /// @@ -285,6 +264,6 @@ public class PluginDetectionSyncJobTests private static Guid DeriveExpectedId(string assemblyName) { byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(assemblyName)); - return new Guid(hash.Take(16).ToArray()); + return new Guid([.. hash.Take(16)]); } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs index c744d920..cb97b6e9 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginInstallerTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; -using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; @@ -27,6 +27,7 @@ public class PluginInstallerTests : IDisposable { private readonly string _pluginsDirectory; private readonly PluginInstaller _sut; + private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -36,7 +37,7 @@ public class PluginInstallerTests : IDisposable _pluginsDirectory = Path.Combine(AppContext.BaseDirectory, $".test-plugins-{Guid.NewGuid():N}"); ILogger mockLogger = Substitute.For>(); IOptions mockOptions = Substitute.For>(); - mockOptions.Value.Returns(new PluginsSettingsDto { Directory = Path.GetFileName(_pluginsDirectory) }); + mockOptions.Value.Returns(_pluginsSettingsDtoFixture.Create(directory: Path.GetFileName(_pluginsDirectory))); _sut = new PluginInstaller(mockOptions, mockLogger); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs index a56dcc62..2679838f 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Infrastructure.Core.Plugins; using Microsoft.Extensions.Logging; @@ -26,6 +27,7 @@ public class PluginSettingsStoreTests private readonly IPluginRepository _mockPluginRepository; private readonly ILogger _mockLogger; private readonly PluginSettingsStore _sut; + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +48,7 @@ public class PluginSettingsStoreTests // Arrange Guid pluginId = Guid.NewGuid(); Dictionary expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" }; - PluginEntity pluginEntity = CreatePluginEntity(pluginId, JsonSerializer.Serialize(expectedSettings)); + PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, settingsJson: JsonSerializer.Serialize(expectedSettings)); _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) .Returns(Result.From(pluginEntity)); @@ -63,7 +65,7 @@ public class PluginSettingsStoreTests { // Arrange Guid pluginId = Guid.NewGuid(); - PluginEntity pluginEntity = CreatePluginEntity(pluginId, settingsJson: null); + PluginEntity pluginEntity = _pluginEntityFixture.Create(id: pluginId, includeSettingsJson: false); _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) .Returns(Result.From(pluginEntity)); @@ -103,26 +105,4 @@ public class PluginSettingsStoreTests // Assert Assert.Null(result); } - - /// - /// Creates a plugin entity with the provided identity and serialized settings. - /// - /// The Id of the plugin. - /// The serialized settings of the plugin. - /// The created plugin entity. - private static PluginEntity CreatePluginEntity(Guid id, string? settingsJson) - { - return new PluginEntity - { - Id = id, - Name = "Test Plugin", - Author = "Test Author", - Version = "1.0.0", - Description = "Test plugin description", - SettingsJson = settingsJson, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.Empty, - UpdatedBy = null - }; - } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index 7068b692..ba93fd07 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole; -using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -26,6 +28,9 @@ public class AddRoleEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly AddRoleEndpoint _sut; + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -40,9 +45,11 @@ public class AddRoleEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithRoleResponse() { // Arrange - AddRoleRequest request = new("Admin", [Guid.NewGuid()]); + AddRoleRequest request = _addRoleRequestFixture.Create(roleName: "Admin", permissions: [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; - RolePermissionsResponse expectedResponse = new(new RoleDto(Guid.NewGuid(), "Admin"), []); + RolePermissionsResponse expectedResponse = _rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: []); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -58,7 +65,7 @@ public class AddRoleEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - AddRoleRequest request = new("Admin", [Guid.NewGuid()]); + AddRoleRequest request = _addRoleRequestFixture.Create(roleName: "Admin", permissions: [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Creation.Failed", "Failed to create role."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -84,10 +91,12 @@ public class AddRoleEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendAddRoleCommandToSender() { // Arrange - AddRoleRequest request = new("Admin", [Guid.NewGuid()]); + AddRoleRequest request = _addRoleRequestFixture.Create(roleName: "Admin", permissions: [Guid.NewGuid()]); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), []))); + .Returns(Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: []))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -114,11 +123,13 @@ public class AddRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new RolePermissionsResponse(new RoleDto(Guid.NewGuid(), "Admin"), [])); + return Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: [])); }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new AddRoleRequest("Admin", []), cts.Token); + Task operationTask = _sut.ExecuteAsync(_addRoleRequestFixture.Create(roleName: "Admin", permissions: []), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs index 4f8be6da..6ca63441 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/DeleteRole/DeleteRoleEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.DeleteRole; @@ -23,6 +24,7 @@ public class DeleteRoleEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly DeleteRoleEndpoint _sut; + private readonly DeleteRoleRequestFixture _deleteRoleRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -37,7 +39,7 @@ public class DeleteRoleEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContent() { // Arrange - DeleteRoleRequest request = new(Guid.NewGuid()); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Deleted)); @@ -53,7 +55,7 @@ public class DeleteRoleEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - DeleteRoleRequest request = new(Guid.NewGuid()); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Deletion.Failed", "Failed to delete role."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -80,7 +82,7 @@ public class DeleteRoleEndpointTests { // Arrange Guid roleId = Guid.NewGuid(); - DeleteRoleRequest request = new(roleId); + DeleteRoleRequest request = _deleteRoleRequestFixture.Create(roleId: roleId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Result.Deleted)); @@ -112,7 +114,7 @@ public class DeleteRoleEndpointTests }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new DeleteRoleRequest(Guid.NewGuid()), cts.Token); + Task operationTask = _sut.ExecuteAsync(_deleteRoleRequestFixture.Create(), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs index a6804307..dc159cc9 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRolePermissions/GetRolePermissionsEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions; -using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -26,6 +28,10 @@ public class GetRolePermissionsEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetRolePermissionsEndpoint _sut; + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly GetRolePermissionsRequestFixture _getRolePermissionsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -40,11 +46,11 @@ public class GetRolePermissionsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPermissions() { // Arrange - GetRolePermissionsRequest request = new(Guid.NewGuid()); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - RolePermissionsResponse expectedResponse = new( - new RoleDto(Guid.NewGuid(), "Admin"), - [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] + RolePermissionsResponse expectedResponse = _rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: [_permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)] ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -61,7 +67,7 @@ public class GetRolePermissionsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetRolePermissionsRequest request = new(Guid.NewGuid()); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Permissions.NotFound", "Role permissions not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -88,12 +94,12 @@ public class GetRolePermissionsEndpointTests { // Arrange Guid roleId = Guid.NewGuid(); - GetRolePermissionsRequest request = new(roleId); + GetRolePermissionsRequest request = _getRolePermissionsRequestFixture.Create(roleId: roleId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "Admin"), - [] + .Returns(Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: [] ))); // Act @@ -119,14 +125,14 @@ public class GetRolePermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "Admin"), - [] + return Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "Admin"), + permissions: [] )); }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new GetRolePermissionsRequest(Guid.NewGuid()), cts.Token); + Task operationTask = _sut.ExecuteAsync(_getRolePermissionsRequestFixture.Create(), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs index 5cf487fa..ef0ae8d6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/GetRoles/GetRolesEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Admin.Authorization.Roles.GetRoles; @@ -25,6 +26,7 @@ public class GetRolesEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetRolesEndpoint _sut; + private readonly RoleResponseFixture _roleResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,8 +44,8 @@ public class GetRolesEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = [ - new RoleResponse(Guid.NewGuid(), "Admin") - ]; + _roleResponseFixture.Create(roleName: "Admin") + ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -88,7 +90,7 @@ public class GetRolesEndpointTests _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(new List { - new(Guid.NewGuid(), "Admin") + _roleResponseFixture.Create(roleName: "Admin") } as IEnumerable)); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs index 9f32b1d3..dd210b29 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Admin/Authorization/Roles/UpdateRole/UpdateRoleEndpointTests.cs @@ -1,7 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole; -using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -27,6 +29,10 @@ public class UpdateRoleEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly UpdateRoleEndpoint _sut; + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -41,11 +47,11 @@ public class UpdateRoleEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedRole() { // Arrange - UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: "UpdatedAdmin"); CancellationToken cancellationToken = CancellationToken.None; - RolePermissionsResponse expectedResponse = new( - new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), - [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)] + RolePermissionsResponse expectedResponse = _rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "UpdatedAdmin"), + permissions: [_permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanViewUsers)] ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -62,7 +68,7 @@ public class UpdateRoleEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: "UpdatedAdmin"); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Role.Update.Failed", "Failed to update role."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -88,12 +94,12 @@ public class UpdateRoleEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateRoleCommandToSender() { // Arrange - UpdateRoleRequest request = new(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]); + UpdateRoleRequest request = _updateRoleRequestFixture.Create(roleName: "UpdatedAdmin"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), - [] + .Returns(Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "UpdatedAdmin"), + permissions: [] ))); // Act @@ -122,15 +128,15 @@ public class UpdateRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new RolePermissionsResponse( - new RoleDto(Guid.NewGuid(), "UpdatedAdmin"), - [] + return Result.From(_rolePermissionsResponseFixture.Create( + role: _roleDtoFixture.Create(roleName: "UpdatedAdmin"), + permissions: [] )); }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync( - new UpdateRoleRequest(Guid.NewGuid(), "UpdatedAdmin", [Guid.NewGuid()]), + _updateRoleRequestFixture.Create(roleName: "UpdatedAdmin"), cts.Token); await operationStarted.Task; cts.Cancel(); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index d6c06761..b1836ba6 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -2,8 +2,9 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem; -using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -24,6 +25,7 @@ public class GetTypeEndpointTests { private readonly IQueryHandler _mockHandler; private readonly GetTypeEndpoint _sut; + private readonly FileSystemTypeResponseFixture _fileSystemTypeResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -39,7 +41,7 @@ public class GetTypeEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new(PlatformType.Windows); + FileSystemTypeResponse expectedResponse = _fileSystemTypeResponseFixture.Create(platformType: PlatformType.Windows); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -58,7 +60,7 @@ public class GetTypeEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - FileSystemTypeResponse expectedResponse = new(platformType); + FileSystemTypeResponse expectedResponse = _fileSystemTypeResponseFixture.Create(platformType: platformType); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -76,7 +78,7 @@ public class GetTypeEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(new FileSystemTypeResponse(PlatformType.Windows)); + .Returns(_fileSystemTypeResponseFixture.Create(platformType: PlatformType.Windows)); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); @@ -99,7 +101,7 @@ public class GetTypeEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return new FileSystemTypeResponse(PlatformType.Windows); + return _fileSystemTypeResponseFixture.Create(platformType: PlatformType.Windows); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index a8e555e9..7f1ce540 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.CheckPathExists; using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; @@ -27,6 +28,7 @@ public class CheckPathExistsEndpointTests private readonly IQueryHandler> _mockHandler; private readonly CheckPathExistsEndpoint _sut; private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new(); + private readonly PathExistsResponseFixture _pathExistsResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class CheckPathExistsEndpointTests // Arrange CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; - PathExistsResponse expectedResponse = new(true); + PathExistsResponse expectedResponse = _pathExistsResponseFixture.Create(exists: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -62,7 +64,7 @@ public class CheckPathExistsEndpointTests CheckPathExistsRequest request = _checkPathExistsRequestFixture.Create(path: @"C:\Users\TestUser\Documents", includeHiddenElements: true); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(new PathExistsResponse(true)); + .Returns(_pathExistsResponseFixture.Create(exists: true)); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -88,7 +90,7 @@ public class CheckPathExistsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new PathExistsResponse(true)); + return Result.From(_pathExistsResponseFixture.Create(exists: true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 530fb3a3..14e9327b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.FileSystemManagement.Paths.Queries.ValidatePath; using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; using Lumina.Contracts.Requests.FileSystemManagement.Path; using Lumina.Contracts.Responses.FileSystemManagement.Path; using Lumina.Domain.Common.Primitives; @@ -27,6 +28,7 @@ public class ValidatePathEndpointTests private readonly IQueryHandler> _mockHandler; private readonly ValidatePathEndpoint _sut; private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); + private readonly PathValidResponseFixture _pathValidResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class ValidatePathEndpointTests // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; - PathValidResponse expectedResponse = new(true); + PathValidResponse expectedResponse = _pathValidResponseFixture.Create(isValid: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -62,7 +64,7 @@ public class ValidatePathEndpointTests ValidatePathRequest request = _validatePathRequestFixture.Create(@"C:\Users\TestUser\Documents"); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(new PathValidResponse(true)); + .Returns(_pathValidResponseFixture.Create(isValid: true)); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -114,7 +116,7 @@ public class ValidatePathEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new PathValidResponse(true)); + return Result.From(_pathValidResponseFixture.Create(isValid: true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs index d32b843a..f4bcac14 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -6,7 +6,6 @@ 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.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -104,7 +103,7 @@ public class AddLibraryEndpointTests command.CoverImage == request.CoverImage && command.IsEnabled == request.IsEnabled && command.IsLocked == request.IsLocked && - command.DownloadMetadataFromWeb == request.DownloadMetadataFromWeb && + command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb && command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan), Arg.Is(cancellationToken)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs index 4031193b..b86bf9ab 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries; @@ -25,6 +26,7 @@ public class ScanLibrariesEndpointTests { private readonly ICommandHandler>> _mockHandler; private readonly ScanLibrariesEndpoint _sut; + private readonly MediaLibraryScanResponseFixture _mediaLibraryScanResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,8 +44,8 @@ public class ScanLibrariesEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponses = [ - new MediaLibraryScanResponse(Guid.NewGuid(), Guid.NewGuid()), - new MediaLibraryScanResponse(Guid.NewGuid(), Guid.NewGuid()) + _mediaLibraryScanResponseFixture.Create(), + _mediaLibraryScanResponseFixture.Create() ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponses)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs index 8e533e4b..04276e5a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; 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; @@ -26,6 +27,7 @@ public class ScanLibraryEndpointTests private readonly ICommandHandler> _mockHandler; private readonly ScanLibraryEndpoint _sut; private readonly ScanLibraryRequestFixture _scanLibraryRequestFixture = new(); + private readonly MediaLibraryScanResponseFixture _mediaLibraryScanResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class ScanLibraryEndpointTests // Arrange ScanLibraryRequest request = _scanLibraryRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - MediaLibraryScanResponse expectedResponse = new(Guid.NewGuid(), request.Id); + MediaLibraryScanResponse expectedResponse = _mediaLibraryScanResponseFixture.Create(libraryId: request.Id); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -87,7 +89,7 @@ public class ScanLibraryEndpointTests ScanLibraryRequest request = _scanLibraryRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new MediaLibraryScanResponse(Guid.NewGuid(), request.Id))); + .Returns(Result.From(_mediaLibraryScanResponseFixture.Create(libraryId: request.Id))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -113,7 +115,7 @@ public class ScanLibraryEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new MediaLibraryScanResponse(Guid.NewGuid(), request.Id)); + return Result.From(_mediaLibraryScanResponseFixture.Create(libraryId: request.Id)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs index d7e2d21d..b84eddcb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -6,7 +6,6 @@ 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.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -106,7 +105,7 @@ public class UpdateLibraryEndpointTests command.CoverImage == request.CoverImage && command.IsEnabled == request.IsEnabled && command.IsLocked == request.IsLocked && - command.DownloadMetadataFromWeb == request.DownloadMetadataFromWeb && + command.CanDownloadMetadataFromWeb == request.CanDownloadMetadataFromWeb && command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan), Arg.Is(cancellationToken)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs index a0bd0b67..7465f8f2 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; using Microsoft.AspNetCore.Http; @@ -19,12 +20,13 @@ namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenConten public class GetBookEndpointTests { private readonly GetBookEndpoint _sut = Factory.Create(); + private readonly GetBookRequestFixture _getBookRequestFixture = new(); [Fact] public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResult() { // Arrange - GetBookRequest request = new(Guid.NewGuid().ToString()); + GetBookRequest request = _getBookRequestFixture.Create(id: Guid.NewGuid().ToString()); CancellationToken cancellationToken = CancellationToken.None; // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 508ab4b6..7183f83e 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -2,15 +2,14 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Responses.Common; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Errors; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -34,6 +33,7 @@ public class GetBooksEndpointTests private readonly GetBooksEndpoint _sut; private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); private readonly BookResponseFixture _bookResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -171,19 +171,12 @@ public class GetBooksEndpointTests /// /// The number of book responses to include in the data collection. /// A configured paginated response instance. - private static PaginatedResponse CreatePaginatedResponse(int bookCount, BookResponseFixture bookResponseFixture) + private PaginatedResponse CreatePaginatedResponse(int bookCount, BookResponseFixture bookResponseFixture) { List books = []; for (int index = 0; index < bookCount; index++) books.Add(bookResponseFixture.Create()); - return new PaginatedResponse - { - Data = books, - CurrentPage = 1, - PerPage = 10, - Count = bookCount, - NumberOfPages = bookCount > 0 ? 1 : 0 - }; + return _paginatedResponseFixture.Create(data: books, currentPage: 1, perPage: 10, count: bookCount, numberOfPages: bookCount > 0 ? 1 : 0); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index 3a2a43c7..a222d23c 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -3,11 +3,13 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite; using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Fixtures.Responses.Common; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -30,6 +32,8 @@ public class GetBooksLiteEndpointTests private readonly IQueryHandler>> _mockHandler; private readonly GetBooksLiteEndpoint _sut; private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + private readonly BookLiteResponseFixture _bookLiteResponseFixture = new(); + private readonly PaginatedResponseFixture _paginatedResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -167,24 +171,17 @@ public class GetBooksLiteEndpointTests /// /// The number of book responses to include in the data collection. /// A configured paginated response instance. - private static PaginatedResponse CreatePaginatedResponse(int bookCount) + private PaginatedResponse CreatePaginatedResponse(int bookCount) { List books = []; for (int index = 0; index < bookCount; index++) - books.Add(new BookLiteResponse( - Id: Guid.NewGuid(), - Title: "Test Book", - ReleaseYear: 2001, - CoverPath: null + books.Add(_bookLiteResponseFixture.Create( + id: Guid.NewGuid(), + title: "Test Book", + releaseYear: 2001, + coverPath: null )); - return new PaginatedResponse - { - Data = books, - CurrentPage = 1, - PerPage = 10, - Count = bookCount, - NumberOfPages = bookCount > 0 ? 1 : 0 - }; + return _paginatedResponseFixture.Create(data: books, currentPage: 1, perPage: 10, count: bookCount, numberOfPages: bookCount > 0 ? 1 : 0); } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs index 362c8e7d..e95176ec 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/CheckInitializationEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Queries.CheckInitialization; +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement; using Lumina.Contracts.Responses.UsersManagement; using Lumina.Presentation.Api.Core.Endpoints.Maintenance.ApplicationSetup; using Microsoft.AspNetCore.Http; @@ -23,6 +24,7 @@ public class CheckInitializationEndpointTests { private readonly IQueryHandler _mockHandler; private readonly CheckInitializationEndpoint _sut; + private readonly InitializationResponseFixture _initializationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -38,7 +40,7 @@ public class CheckInitializationEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - InitializationResponse expectedResponse = new(IsInitialized: true); + InitializationResponse expectedResponse = _initializationResponseFixture.Create(isInitialized: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); @@ -56,7 +58,7 @@ public class CheckInitializationEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(new InitializationResponse(IsInitialized: true)); + .Returns(_initializationResponseFixture.Create(isInitialized: true)); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); @@ -81,7 +83,7 @@ public class CheckInitializationEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return new InitializationResponse(IsInitialized: true); + return _initializationResponseFixture.Create(isInitialized: true); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs index b6077b29..4ad1b481 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/ApplicationSetup/SetupApplicationEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Maintenance.ApplicationSetup.Commands.SetupApplication; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -26,6 +27,7 @@ public class SetupApplicationEndpointTests private readonly ICommandHandler> _mockHandler; private readonly SetupApplicationEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + private readonly RegistrationResponseFixture _registrationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class SetupApplicationEndpointTests // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + RegistrationResponse expectedResponse = _registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -88,7 +90,7 @@ public class SetupApplicationEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + .Returns(Result.From(_registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +120,7 @@ public class SetupApplicationEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + return Result.From(_registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123")); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs index 6351bd06..3cb05f37 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/ChangePassword/ChangePasswordEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.ChangePassword; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -26,6 +27,7 @@ public class ChangePasswordEndpointTests private readonly ICommandHandler> _mockHandler; private readonly ChangePasswordEndpoint _sut; private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + private readonly ChangePasswordResponseFixture _changePasswordResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class ChangePasswordEndpointTests // Arrange ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - ChangePasswordResponse expectedResponse = new(IsPasswordChanged: true); + ChangePasswordResponse expectedResponse = _changePasswordResponseFixture.Create(isPasswordChanged: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -86,7 +88,7 @@ public class ChangePasswordEndpointTests ChangePasswordRequest request = _changePasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new ChangePasswordResponse(true))); + .Returns(Result.From(_changePasswordResponseFixture.Create(isPasswordChanged: true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -116,7 +118,7 @@ public class ChangePasswordEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new ChangePasswordResponse(true)); + return Result.From(_changePasswordResponseFixture.Create(isPasswordChanged: true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs index 8f156ec0..b3d56177 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/GetUsers/GetUsersEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.GetUsers; +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Users; using Lumina.Contracts.Responses.UsersManagement.Users; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Authentication.GetUsers; @@ -25,6 +26,7 @@ public class GetUsersEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetUsersEndpoint _sut; + private readonly UserResponseFixture _userResponseFixture = new(); /// /// Initializes a new instance of the class. /// @@ -41,7 +43,7 @@ public class GetUsersEndpointTests CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = [ - new UserResponse(Guid.NewGuid(), "testUser", DateTime.UtcNow, null) + _userResponseFixture.Create(username: "testUser", createdOnUtc: DateTime.UtcNow, updatedOnUtc: null) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs index fde135ee..dc2c2d7d 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Queries.LoginUser; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -27,6 +28,7 @@ public class LoginEndpointTests private readonly IQueryHandler> _mockHandler; private readonly LoginEndpoint _sut; private readonly LoginRequestFixture _loginRequestFixture = new(); + private readonly LoginResponseFixture _loginResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class LoginEndpointTests // Arrange LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - LoginResponse expectedResponse = new(Guid.NewGuid(), "testUser", "jwt_token", true); + LoginResponse expectedResponse = _loginResponseFixture.Create(username: "testUser", token: "jwt_token", usesTotp: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -87,7 +89,7 @@ public class LoginEndpointTests LoginRequest request = _loginRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true))); + .Returns(Result.From(_loginResponseFixture.Create(username: "testUser", token: "jwt_token", usesTotp: true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -116,7 +118,7 @@ public class LoginEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new LoginResponse(Guid.NewGuid(), "testUser", "jwt_token", true)); + return Result.From(_loginResponseFixture.Create(username: "testUser", token: "jwt_token", usesTotp: true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index 79250010..b1a1bf19 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RecoverPassword; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -26,6 +27,7 @@ public class RecoverPasswordEndpointTests private readonly ICommandHandler> _mockHandler; private readonly RecoverPasswordEndpoint _sut; private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly RecoverPasswordResponseFixture _recoverPasswordResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class RecoverPasswordEndpointTests // Arrange RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - RecoverPasswordResponse expectedResponse = new(IsPasswordReset: true); + RecoverPasswordResponse expectedResponse = _recoverPasswordResponseFixture.Create(isPasswordReset: true); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -86,7 +88,7 @@ public class RecoverPasswordEndpointTests RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RecoverPasswordResponse(true))); + .Returns(Result.From(_recoverPasswordResponseFixture.Create(isPasswordReset: true))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -114,7 +116,7 @@ public class RecoverPasswordEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new RecoverPasswordResponse(true)); + return Result.From(_recoverPasswordResponseFixture.Create(isPasswordReset: true)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index f7a8184c..1f159251 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -2,6 +2,7 @@ using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authentication.Commands.RegisterUser; using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; using Lumina.Contracts.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.Domain.Common.Primitives; @@ -26,6 +27,7 @@ public class RegisterEndpointTests private readonly ICommandHandler> _mockHandler; private readonly RegisterEndpoint _sut; private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + private readonly RegistrationResponseFixture _registrationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class RegisterEndpointTests // Arrange RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - RegistrationResponse expectedResponse = new(Guid.NewGuid(), "testUser", "TOTP123"); + RegistrationResponse expectedResponse = _registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -87,7 +89,7 @@ public class RegisterEndpointTests RegistrationRequest request = _registrationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123"))); + .Returns(Result.From(_registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -117,7 +119,7 @@ public class RegisterEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new RegistrationResponse(Guid.NewGuid(), "testUser", "TOTP123")); + return Result.From(_registrationResponseFixture.Create(username: "testUser", totpSecret: "TOTP123")); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs index cb9bfaa0..b9a3303a 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetAuthorization/GetAuthorizationEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAuthorization; using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -30,6 +31,7 @@ public class GetAuthorizationEndpointTests private readonly IQueryHandler> _mockHandler; private readonly GetAuthorizationEndpoint _sut; private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); + private readonly AuthorizationResponseFixture _authorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -46,10 +48,10 @@ public class GetAuthorizationEndpointTests // Arrange GetAuthorizationRequest request = _getAuthorizationRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - AuthorizationResponse expectedResponse = new( - request.UserId!.Value, - "Admin", - new HashSet { AuthorizationPermission.CanViewUsers }); + AuthorizationResponse expectedResponse = _authorizationResponseFixture.Create( + userId: request.UserId!.Value, + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers }); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -97,7 +99,7 @@ public class GetAuthorizationEndpointTests CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new AuthorizationResponse( + .Returns(Result.From(_authorizationResponseFixture.Create( request.UserId!.Value, string.Empty, new HashSet().ToHashSet() @@ -128,7 +130,7 @@ public class GetAuthorizationEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new AuthorizationResponse( + return Result.From(_authorizationResponseFixture.Create( request.UserId!.Value, string.Empty, new HashSet().ToHashSet() diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs index b2145950..a8d2aa73 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissions/GetUserPermissionsEndpointTests.cs @@ -2,6 +2,8 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -27,6 +29,8 @@ public class GetUserPermissionsEndpointTests { private readonly IQueryHandler>> _mockHandler; private readonly GetUserPermissionsEndpoint _sut; + private readonly PermissionResponseFixture _permissionResponseFixture = new(); + private readonly GetUserPermissionsRequestFixture _getUserPermissionsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -41,12 +45,12 @@ public class GetUserPermissionsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPermissions() { // Arrange - GetUserPermissionsRequest request = new(Guid.NewGuid()); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; IEnumerable expectedResponse = [ - new PermissionResponse(Guid.NewGuid(), AuthorizationPermission.CanViewUsers), - new PermissionResponse(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers) + _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanViewUsers), + _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -63,7 +67,7 @@ public class GetUserPermissionsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetUserPermissionsRequest request = new(Guid.NewGuid()); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("User.Permissions.NotFound", "User permissions not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -90,7 +94,7 @@ public class GetUserPermissionsEndpointTests { // Arrange Guid userId = Guid.NewGuid(); - GetUserPermissionsRequest request = new(userId); + GetUserPermissionsRequest request = _getUserPermissionsRequestFixture.Create(userId: userId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(Array.Empty() as IEnumerable)); @@ -122,7 +126,7 @@ public class GetUserPermissionsEndpointTests }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new GetUserPermissionsRequest(Guid.NewGuid()), cts.Token); + Task operationTask = _sut.ExecuteAsync(_getUserPermissionsRequestFixture.Create(), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs index 1ec03f87..bf327964 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/GetUserRole/GetUserRoleEndpointTests.cs @@ -2,6 +2,8 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -25,6 +27,8 @@ public class GetUserRoleEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetUserRoleEndpoint _sut; + private readonly RoleResponseFixture _roleResponseFixture = new(); + private readonly GetUserRoleRequestFixture _getUserRoleRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -39,9 +43,9 @@ public class GetUserRoleEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithRole() { // Arrange - GetUserRoleRequest request = new(Guid.NewGuid()); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - RoleResponse expectedResponse = new(Guid.NewGuid(), "Admin"); + RoleResponse expectedResponse = _roleResponseFixture.Create(roleName: "Admin"); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -57,7 +61,7 @@ public class GetUserRoleEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - GetUserRoleRequest request = new(Guid.NewGuid()); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("User.Role.NotFound", "User role not found."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -84,10 +88,10 @@ public class GetUserRoleEndpointTests { // Arrange Guid userId = Guid.NewGuid(); - GetUserRoleRequest request = new(userId); + GetUserRoleRequest request = _getUserRoleRequestFixture.Create(userId: userId); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new RoleResponse(Guid.NewGuid(), "Admin"))); + .Returns(Result.From(_roleResponseFixture.Create(roleName: "Admin"))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -112,11 +116,11 @@ public class GetUserRoleEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new RoleResponse(Guid.NewGuid(), "Admin")); + return Result.From(_roleResponseFixture.Create(roleName: "Admin")); }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new GetUserRoleRequest(Guid.NewGuid()), cts.Token); + Task operationTask = _sut.ExecuteAsync(_getUserRoleRequestFixture.Create(), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs index c7c93607..ab154a3b 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Authorization/UpdateUserRoleAndPermissions/UpdateUserRoleAndPermissionsEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions; +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; using Lumina.Contracts.Requests.Authorization; using Lumina.Contracts.Responses.Authorization; using Lumina.Domain.Common.Primitives; @@ -27,6 +29,8 @@ public class UpdateUserRoleAndPermissionsEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly UpdateUserRoleAndPermissionsEndpoint _sut; + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + private readonly AuthorizationResponseFixture _authorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -41,16 +45,11 @@ public class UpdateUserRoleAndPermissionsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithAuthorization() { // Arrange - UpdateUserRoleAndPermissionsRequest request = new( - Guid.NewGuid(), - Guid.NewGuid(), - [Guid.NewGuid()] - ); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - AuthorizationResponse expectedResponse = new( - Guid.NewGuid(), - "Admin", - new HashSet { AuthorizationPermission.CanViewUsers } + AuthorizationResponse expectedResponse = _authorizationResponseFixture.Create( + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers } ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -67,11 +66,7 @@ public class UpdateUserRoleAndPermissionsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - UpdateUserRoleAndPermissionsRequest request = new( - Guid.NewGuid(), - Guid.NewGuid(), - [Guid.NewGuid()] - ); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Failure("Authorization.Update.Failed", "Failed to update user role and permissions."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -97,17 +92,12 @@ public class UpdateUserRoleAndPermissionsEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserRoleAndPermissionsCommandToSender() { // Arrange - UpdateUserRoleAndPermissionsRequest request = new( - Guid.NewGuid(), - Guid.NewGuid(), - [Guid.NewGuid()] - ); + UpdateUserRoleAndPermissionsRequest request = _updateUserRoleAndPermissionsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new AuthorizationResponse( - Guid.NewGuid(), - "Admin", - new HashSet { AuthorizationPermission.CanViewUsers } + .Returns(Result.From(_authorizationResponseFixture.Create( + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers } ))); // Act @@ -136,16 +126,15 @@ public class UpdateUserRoleAndPermissionsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new AuthorizationResponse( - Guid.NewGuid(), - "Admin", - new HashSet { AuthorizationPermission.CanViewUsers } + return Result.From(_authorizationResponseFixture.Create( + role: "Admin", + permissions: new HashSet { AuthorizationPermission.CanViewUsers } )); }, info.Arg())); // Act Task operationTask = _sut.ExecuteAsync( - new UpdateUserRoleAndPermissionsRequest(Guid.NewGuid(), Guid.NewGuid(), [Guid.NewGuid()]), + _updateUserRoleAndPermissionsRequestFixture.Create(), cts.Token); await operationStarted.Task; cts.Cancel(); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs index b56c9832..72e3e1a8 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/ApiHttpClientTests.cs @@ -5,6 +5,7 @@ using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Fixtures.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using NSubstitute; @@ -26,7 +27,7 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Api; [ExcludeFromCodeCoverage] public class ApiHttpClientTests { - private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new(); [Fact] public async Task GetAsync_WhenApiReturnsSuccess_ShouldDeserializeResponseContent() @@ -36,7 +37,7 @@ public class ApiHttpClientTests ApiHttpClient sut = CreateSut(messageHandler); // Act - Lumina.Presentation.Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync("libraries", CancellationToken.None); + Web.Common.DTO.Libraries.LibraryDto[] result = await sut.GetAsync("libraries", CancellationToken.None); // Assert Assert.Single(result); @@ -152,21 +153,35 @@ public class ApiHttpClientTests Assert.Equal("image/png", blob.ContentType); } - private static ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null) + /// + /// Creates the system under test configured with the provided message handler. + /// + /// The message handler backing the inner . + /// Optional token claim to place on the current HTTP context user. + /// The created . + private ApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null) { HttpClient httpClient = new(messageHandler); IHttpContextAccessor httpContextAccessor = Substitute.For(); if (token is not null) { - DefaultHttpContext httpContext = new(); - httpContext.User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication")); + DefaultHttpContext httpContext = new() + { + User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("Token", token)], "TestAuthentication")) + }; httpContextAccessor.HttpContext.Returns(httpContext); } IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); - serverConfigurationOptions.Value.Returns(new ServerConfigurationDto { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }); + serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214)); return new ApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions); } + /// + /// Creates an with the given status code and JSON body. + /// + /// The HTTP status code of the response. + /// The JSON payload of the response body. + /// The created . private static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) { return new HttpResponseMessage(statusCode) diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs index de8002c4..403fa2c9 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Authorization/AuthorizationServiceTests.cs @@ -3,6 +3,7 @@ using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.Authorization; using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Responses.Authorization; +using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization; using Microsoft.AspNetCore.Http; using NSubstitute; using System; @@ -23,6 +24,7 @@ public class AuthorizationServiceTests private readonly IApiHttpClient _mockApiHttpClient; private readonly AuthorizationService _sut; private readonly Guid _userId; + private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class AuthorizationServiceTests { // Arrange _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanCreateLibraries])); + .Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanCreateLibraries])); // Act bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); @@ -57,7 +59,7 @@ public class AuthorizationServiceTests { // Arrange _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new GetAuthorizationResponse(_userId, "Admin", [AuthorizationPermission.CanViewUsers])); + .Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [AuthorizationPermission.CanViewUsers])); // Act bool result = await _sut.HasPermissionAsync(AuthorizationPermission.CanCreateLibraries, CancellationToken.None); @@ -71,7 +73,7 @@ public class AuthorizationServiceTests { // Arrange _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + .Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [])); // Act bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); @@ -85,7 +87,7 @@ public class AuthorizationServiceTests { // Arrange _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new GetAuthorizationResponse(_userId, "User", [])); + .Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "User", permissions: [])); // Act bool result = await _sut.IsInRoleAsync("Admin", CancellationToken.None); @@ -99,7 +101,7 @@ public class AuthorizationServiceTests { // Arrange _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new GetAuthorizationResponse(_userId, "Admin", [])); + .Returns(_getAuthorizationResponseFixture.Create(userId: _userId, role: "Admin", permissions: [])); // Act await _sut.HasPermissionAsync(AuthorizationPermission.CanViewUsers, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs index 6929a5f3..51c156c6 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Security/CryptographyServiceTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.Security; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; using Microsoft.Extensions.Options; using System; using System.Diagnostics.CodeAnalysis; @@ -15,6 +16,7 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Security; public class CryptographyServiceTests { private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new(); private readonly CryptographyService _sut; /// @@ -22,7 +24,7 @@ public class CryptographyServiceTests /// public CryptographyServiceTests() { - EncryptionSettingsDto settings = new() { SecretKey = TEST_ENCRYPTION_KEY }; + EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: TEST_ENCRYPTION_KEY); _sut = new CryptographyService(Options.Create(settings)); } @@ -30,25 +32,25 @@ public class CryptographyServiceTests public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext() { // Arrange - const string plaintext = "sensitive-data"; + const string PLAINTEXT = "sensitive-data"; // Act - string ciphertext = _sut.Encrypt(plaintext); + string ciphertext = _sut.Encrypt(PLAINTEXT); // Assert - Assert.NotEqual(plaintext, ciphertext); - Assert.Equal(plaintext, _sut.Decrypt(ciphertext)); + Assert.NotEqual(PLAINTEXT, ciphertext); + Assert.Equal(PLAINTEXT, _sut.Decrypt(ciphertext)); } [Fact] public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts() { // Arrange - const string plaintext = "sensitive-data"; + const string PLAINTEXT = "sensitive-data"; // Act - string firstCiphertext = _sut.Encrypt(plaintext); - string secondCiphertext = _sut.Encrypt(plaintext); + string firstCiphertext = _sut.Encrypt(PLAINTEXT); + string secondCiphertext = _sut.Encrypt(PLAINTEXT); // Assert Assert.NotEqual(firstCiphertext, secondCiphertext); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs index 33365464..f31f5460 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/EncryptionSettingsModelValidatorTests.cs @@ -2,6 +2,7 @@ using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Validators; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; using Lumina.Presentation.Web.UnitTests.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,13 +17,14 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Validators; public class EncryptionSettingsModelValidatorTests { private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; + private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new(); private readonly EncryptionSettingsDtoValidator _validator = new(); [Fact] public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError() { // Arrange - EncryptionSettingsDto settings = new() { SecretKey = string.Empty }; + EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: string.Empty); // Act List result = _validator.TestValidate(settings); @@ -35,7 +37,7 @@ public class EncryptionSettingsModelValidatorTests public void Validate_WhenSecretKeyIsNotBase64_ShouldHaveValidationError() { // Arrange - EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" }; + EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: "not-base64-key!"); // Act List result = _validator.TestValidate(settings); @@ -48,7 +50,7 @@ public class EncryptionSettingsModelValidatorTests public void Validate_WhenSecretKeyIsValidBase64_ShouldNotHaveValidationError() { // Arrange - EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY }; + EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: VALID_BASE64_KEY); // Act List result = _validator.TestValidate(settings); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs index 94ae0008..d0c80f92 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Validators/ServerConfigurationModelValidatorTests.cs @@ -2,6 +2,7 @@ using Lumina.Presentation.Web.Common.DTO.Configuration; using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Validators; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; using Lumina.Presentation.Web.UnitTests.Common.Setup; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -15,13 +16,14 @@ namespace Lumina.Presentation.Web.UnitTests.Common.Validators; [ExcludeFromCodeCoverage] public class ServerConfigurationModelValidatorTests { + private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new(); private readonly ServerConfigurationDtoValidator _validator = new(); [Fact] public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError() { // Arrange - ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 }; + ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: string.Empty, port: 5214); // Act List result = _validator.TestValidate(configuration); @@ -36,7 +38,7 @@ public class ServerConfigurationModelValidatorTests public void Validate_WhenPortIsAtBoundary_ShouldNotHaveValidationError(ushort port) { // Arrange - ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port }; + ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: port); // Act List result = _validator.TestValidate(configuration); @@ -51,7 +53,7 @@ public class ServerConfigurationModelValidatorTests public void Validate_WhenApiVersionIsAtBoundary_ShouldNotHaveValidationError(char apiVersion) { // Arrange - ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 }; + ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: apiVersion, baseAddress: "http://localhost", port: 5214); // Act List result = _validator.TestValidate(configuration); @@ -64,7 +66,7 @@ public class ServerConfigurationModelValidatorTests public void Validate_WhenConfigurationIsValid_ShouldNotHaveValidationError() { // Arrange - ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 }; + ServerConfigurationDto configuration = _serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214); // Act List result = _validator.TestValidate(configuration); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs index b3ac71bf..a155016a 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Authorization/Roles/AddRole/AddRoleEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Requests.Authorization; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Authorization.Roles.AddRole; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Authorization; using Lumina.Presentation.Web.Fixtures.Common.Requests.Authorization; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; @@ -29,6 +30,9 @@ public class AddRoleEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly AddRoleEndpoint _sut; private readonly AddRoleRequestFixture _addRoleRequestFixture = new(); + private readonly RoleDtoFixture _roleDtoFixture = new(); + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly RolePermissionsDtoFixture _rolePermissionsDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -44,7 +48,7 @@ public class AddRoleEndpointTests { // Arrange AddRoleRequest request = _addRoleRequestFixture.Create(); - RolePermissionsDto expectedResponse = new(new RoleDto(Guid.NewGuid(), request.RoleName!), [new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanViewUsers)]); + RolePermissionsDto expectedResponse = _rolePermissionsDtoFixture.Create(role: _roleDtoFixture.Create(id: Guid.NewGuid(), roleName: request.RoleName!), permissions: [_permissionDtoFixture.Create(id: Guid.NewGuid(), permission: AuthorizationPermission.CanViewUsers)]); _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(expectedResponse); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs index f659d122..9caca737 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DeleteTheme/DeleteThemeEndpointTests.cs @@ -1,15 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DeleteTheme; using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -25,6 +24,7 @@ public class DeleteThemeEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly DeleteThemeEndpoint _sut; + private readonly DeleteThemeRequestFixture _deleteThemeRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -43,14 +43,12 @@ public class DeleteThemeEndpointTests string themeId = "editorial-paper"; // Act - IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_deleteThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert using (System.Text.Json.JsonDocument jsonDocument = System.Text.Json.JsonDocument.Parse(body)) - { Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); - } } [Fact] @@ -61,7 +59,7 @@ public class DeleteThemeEndpointTests string expectedEndpoint = ApiRoutes.Themes.DELETE_THEME.Replace("{themeId}", themeId); // Act - await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + await _sut.ExecuteAsync(_deleteThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert await _mockApiHttpClient.Received(1).DeleteAsync(expectedEndpoint, Arg.Any()); @@ -74,7 +72,7 @@ public class DeleteThemeEndpointTests public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) { // Act - IResult result = await _sut.ExecuteAsync(new DeleteThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_deleteThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert ProblemHttpResult problemResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs index 3176061a..f53865a0 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/DownloadTheme/DownloadThemeEndpointTests.cs @@ -2,16 +2,15 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.DownloadTheme; using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; -using System.IO; using System.Threading; using System.Threading.Tasks; #endregion @@ -26,6 +25,8 @@ public class DownloadThemeEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly DownloadThemeEndpoint _sut; + private readonly GetThemeArchiveRequestFixture _getThemeArchiveRequestFixture = new(); + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -43,10 +44,10 @@ public class DownloadThemeEndpointTests // Arrange string themeId = "editorial-paper"; _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) - .Returns(new BlobDataDto { Data = [0x50, 0x4B, 0x03, 0x04], ContentType = "application/zip" }); + .Returns(_blobDataDtoFixture.Create(data: [0x50, 0x4B, 0x03, 0x04], contentType: "application/zip")); // Act - IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getThemeArchiveRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert FileStreamHttpResult fileResult = Assert.IsType(result); @@ -61,10 +62,10 @@ public class DownloadThemeEndpointTests string themeId = "editorial-paper"; string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId); _mockApiHttpClient.GetBlobAsync(expectedEndpoint, Arg.Any()) - .Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "application/zip" }); + .Returns(_blobDataDtoFixture.Create(data: [1, 2, 3], contentType: "application/zip")); // Act - await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + await _sut.ExecuteAsync(_getThemeArchiveRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert await _mockApiHttpClient.Received(1).GetBlobAsync(expectedEndpoint, Arg.Any()); @@ -77,7 +78,7 @@ public class DownloadThemeEndpointTests public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) { // Act - IResult result = await _sut.ExecuteAsync(new GetThemeArchiveRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getThemeArchiveRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert ProblemHttpResult problemResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs index 96d7f0f1..83ece510 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/RestoreTheme/RestoreThemeEndpointTests.cs @@ -2,15 +2,14 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Themes; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.RestoreTheme; using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -26,6 +25,7 @@ public class RestoreThemeEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly RestoreThemeEndpoint _sut; + private readonly RestoreThemeRequestFixture _restoreThemeRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -44,7 +44,7 @@ public class RestoreThemeEndpointTests string themeId = "editorial-paper"; // Act - IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_restoreThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert @@ -62,7 +62,7 @@ public class RestoreThemeEndpointTests string expectedEndpoint = ApiRoutes.Themes.RESTORE_THEME.Replace("{themeId}", themeId); // Act - await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + await _sut.ExecuteAsync(_restoreThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert await _mockApiHttpClient.Received(1).PostAsync(expectedEndpoint, Arg.Any(), Arg.Any()); @@ -75,7 +75,7 @@ public class RestoreThemeEndpointTests public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) { // Act - IResult result = await _sut.ExecuteAsync(new RestoreThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_restoreThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert ProblemHttpResult problemResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs index 667c03a7..9f029c82 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Admin/Themes/SetCurrentTheme/SetCurrentThemeEndpointTests.cs @@ -2,16 +2,15 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DTO.Themes; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Admin.Themes.SetCurrentTheme; using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -28,6 +27,7 @@ public class SetCurrentThemeEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly SetCurrentThemeEndpoint _sut; private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly SetCurrentThemeRequestFixture _setCurrentThemeRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -48,7 +48,7 @@ public class SetCurrentThemeEndpointTests .Returns(_themeResponseDtoFixture.Create()); // Act - IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_setCurrentThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert @@ -68,7 +68,7 @@ public class SetCurrentThemeEndpointTests public async Task ExecuteAsync_WhenThemeIdIsBlank_ShouldReturnProblemWithBadRequest(string? themeId) { // Act - IResult result = await _sut.ExecuteAsync(new SetCurrentThemeRequest(themeId), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_setCurrentThemeRequestFixture.Create(themeId: themeId), CancellationToken.None); // Assert ProblemHttpResult problemResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs index 94b232f8..cd7c6294 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Directories/GetDirectories/GetDirectoriesEndpointTests.cs @@ -5,6 +5,7 @@ using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Directories; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Directories.GetDirectories; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Directories; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; @@ -27,6 +28,7 @@ public class GetDirectoriesEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly GetDirectoriesEndpoint _sut; private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); + private readonly DirectoryDtoFixture _directoryDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class GetDirectoriesEndpointTests { // Arrange GetDirectoriesRequest request = _getDirectoriesRequestFixture.Create(path: "/media", includeHiddenElements: true); - DirectoryDto[] expectedDirectories = [new DirectoryDto { Path = "/media/books", Name = "books" }]; + DirectoryDto[] expectedDirectories = [_directoryDtoFixture.Create(path: "/media/books", name: "books")]; _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedDirectories); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs index a9da73d8..291f70ae 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/FileSystemManagement/Path/ValidatePath/ValidatePathEndpointTests.cs @@ -5,6 +5,7 @@ using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.Requests.FileSystemManagement.Path; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.FileSystemManagement.Path.ValidatePath; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Fixtures.Common.Requests.FileSystemManagement.Path; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; @@ -27,6 +28,7 @@ public class ValidatePathEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly ValidatePathEndpoint _sut; private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); + private readonly PathValidDtoFixture _pathValidDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -43,7 +45,7 @@ public class ValidatePathEndpointTests // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(path: "/media/books"); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new PathValidDto(true)); + .Returns(_pathValidDtoFixture.Create(isValid: true)); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); @@ -63,7 +65,7 @@ public class ValidatePathEndpointTests // Arrange ValidatePathRequest request = _validatePathRequestFixture.Create(path: "C:/invalid|path"); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new PathValidDto(false)); + .Returns(_pathValidDtoFixture.Create(isValid: false)); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs index 13a5562f..dabae867 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Web.Common.Enums.Common; using Lumina.Presentation.Web.Common.Requests.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetLibraryItems; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; using Lumina.Presentation.Web.Fixtures.Common.Requests.Libraries; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; @@ -29,6 +30,8 @@ public class GetLibraryItemsEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly GetLibraryItemsEndpoint _sut; private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + private readonly PaginatedBookLiteDtoFixture _paginatedBookLiteDtoFixture = new(); + private readonly BookLiteDtoFixture _bookLiteDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -48,11 +51,11 @@ public class GetLibraryItemsEndpointTests perPage: 48, searchTerm: "the hobbit", filterAlphaKey: "H", - ignoreThePrefixForAlphaPicker: true, + shouldIgnoreThePrefixForAlphaPicker: true, sortBy: "title", sortOrder: SortOrder.Ascending); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new PaginatedBookLiteDto()); + .Returns(_paginatedBookLiteDtoFixture.Create()); // Act await _sut.ExecuteAsync(request, CancellationToken.None); @@ -66,7 +69,7 @@ public class GetLibraryItemsEndpointTests endpoint.Contains("perPage=48") && endpoint.Contains("searchTerm=the%20hobbit") && endpoint.Contains("filterAlphaKey=H") && - endpoint.Contains("ignoreThePrefixForAlphaPicker=True") && + endpoint.Contains("shouldIgnoreThePrefixForAlphaPicker=True") && endpoint.Contains("sortBy=title") && endpoint.Contains("sortOrder=Ascending")), Arg.Any()); @@ -78,7 +81,7 @@ public class GetLibraryItemsEndpointTests // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) - .Returns(new PaginatedBookLiteDto()); + .Returns(_paginatedBookLiteDtoFixture.Create()); // Act await _sut.ExecuteAsync(request, CancellationToken.None); @@ -87,7 +90,7 @@ public class GetLibraryItemsEndpointTests await _mockApiHttpClient.Received(1).GetAsync( Arg.Is(endpoint => endpoint.StartsWith(ApiRoutes.Books.GET_BOOKS_LITE, StringComparison.OrdinalIgnoreCase) && - endpoint.EndsWith($"libraryId={request.LibraryId}&ignoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && + endpoint.EndsWith($"libraryId={request.LibraryId}&shouldIgnoreThePrefixForAlphaPicker=False", StringComparison.OrdinalIgnoreCase) && !endpoint.Contains("currentPage=") && !endpoint.Contains("searchTerm=") && !endpoint.Contains("sortBy=")), @@ -99,14 +102,12 @@ public class GetLibraryItemsEndpointTests { // Arrange GetBooksLiteRequest request = _getBooksLiteRequestFixture.Create(); - PaginatedBookLiteDto expectedResponse = new() - { - CurrentPage = 1, - PerPage = 48, - Count = 1, - NumberOfPages = 1, - Data = [new BookLiteDto { Id = Guid.NewGuid(), Title = "Test Book" }] - }; + PaginatedBookLiteDto expectedResponse = _paginatedBookLiteDtoFixture.Create( + data: [_bookLiteDtoFixture.Create(title: "Test Book")], + currentPage: 1, + perPage: 48, + count: 1, + numberOfPages: 1); _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) .Returns(expectedResponse); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs index a0d00dc3..e93f06a1 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/Index/BooksIndexViewEndpointTests.cs @@ -5,19 +5,19 @@ using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Primitives; -using Lumina.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.Index; using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.Extensions.Localization; using NSubstitute; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -38,6 +38,8 @@ public class BooksIndexViewEndpointTests private readonly IStringLocalizer _mockStringLocalizer; private readonly BooksIndexViewEndpoint _sut; private readonly LibraryDtoFixture _libraryDtoFixture = new(); + private readonly GetBooksViewRequestFixture _getBooksViewRequestFixture = new(); + private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -63,7 +65,7 @@ public class BooksIndexViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); // Act - IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(null), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: null), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); @@ -82,10 +84,10 @@ public class BooksIndexViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Books.GET_LIBRARY_ITEMS).Returns("http://localhost/en-us/library/written-content-library/books-library/books/api-get-library-items"); _mockUrlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS).Returns("http://localhost/en-us/tools/settings/api-get-user-settings"); _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(Result.From(new ThemePageRenderResultDto("
content
", ""))); + .Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "
content
", script: ""))); // Act - IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None); // Assert Assert.IsType(result); @@ -115,7 +117,7 @@ public class BooksIndexViewEndpointTests .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); // Act - IResult result = await _sut.ExecuteAsync(new GetBooksViewRequest(expectedLibrary.Id), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getBooksViewRequestFixture.Create(libraryId: expectedLibrary.Id), CancellationToken.None); // Assert Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs index 182c9993..6af7c676 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Themes/ThemeAssets/ThemeAssetsEndpointTests.cs @@ -1,14 +1,13 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; -using Lumina.Presentation.Web.Common.Requests.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Themes.ThemeAssets; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Themes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -24,6 +23,8 @@ public class ThemeAssetsEndpointTests { private readonly IApiHttpClient _mockApiHttpClient; private readonly ThemeAssetsEndpoint _sut; + private readonly GetThemeAssetRequestFixture _getThemeAssetRequestFixture = new(); + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -39,10 +40,10 @@ public class ThemeAssetsEndpointTests { // Arrange _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) - .Returns(new BlobDataDto { Data = [1, 2, 3], ContentType = "text/css" }); + .Returns(_blobDataDtoFixture.Create(data: [1, 2, 3], contentType: "text/css")); // Act - IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: "assets/style.css"), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getThemeAssetRequestFixture.Create(themeId: "editorial-paper", path: "assets/style.css"), CancellationToken.None); // Assert FileContentHttpResult fileResult = Assert.IsType(result); @@ -57,7 +58,7 @@ public class ThemeAssetsEndpointTests public async Task ExecuteAsync_WhenAssetPathMissing_ShouldReturnProblem() { // Act - IResult result = await _sut.ExecuteAsync(new GetThemeAssetRequest(ThemeId: "editorial-paper", Path: null), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_getThemeAssetRequestFixture.Create(themeId: "editorial-paper", path: null), CancellationToken.None); // Assert ProblemHttpResult problemResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs index 6b839637..d38ac904 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Language/SetLanguage/SetLanguageEndpointTests.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; -using Lumina.Presentation.Web.Common.Requests.Tools; using Lumina.Presentation.Web.Core.Endpoints.Tools.Language.SetLanguage; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Tools; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; @@ -20,6 +20,7 @@ namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Language.SetLan public class SetLanguageEndpointTests { private readonly SetLanguageEndpoint _sut; + private readonly SetLanguageRequestFixture _setLanguageRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -36,7 +37,7 @@ public class SetLanguageEndpointTests TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); // Act - IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", null), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_setLanguageRequestFixture.Create(newCulture: "de-DE"), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); @@ -54,7 +55,7 @@ public class SetLanguageEndpointTests TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-us"); // Act - IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("de-DE", "/en-us/tools/settings"), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_setLanguageRequestFixture.Create(newCulture: "de-DE", returnUrl: "/en-us/tools/settings"), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); @@ -69,7 +70,7 @@ public class SetLanguageEndpointTests _sut.HttpContext.Request.PathBase = "/lumina"; // Act - IResult result = await _sut.ExecuteAsync(new SetLanguageRequest("fr-FR", "/en-us/tools/settings"), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_setLanguageRequestFixture.Create(newCulture: "fr-FR", returnUrl: "/en-us/tools/settings"), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs index aa221b50..e47b977c 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Login/LoginViewEndpointTests.cs @@ -1,15 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Http; -using Lumina.Presentation.Web.Common.Requests.UsersManagement.Authentication; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Common.Services; using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Login; +using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement.Authentication; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Threading; @@ -26,6 +25,7 @@ public class LoginViewEndpointTests { private readonly IUrlService _mockUrlService; private readonly LoginViewEndpoint _sut; + private readonly LoginViewRequestFixture _loginViewRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -45,7 +45,7 @@ public class LoginViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED).Returns("http://localhost/en-us"); // Act - IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_loginViewRequestFixture.Create(), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); @@ -57,7 +57,7 @@ public class LoginViewEndpointTests public async Task ExecuteAsync_WhenSuperAdminSetupPending_ShouldRedirectToRegisterView() { // Arrange - Microsoft.AspNetCore.Http.ISession session = Substitute.For(); + ISession session = Substitute.For(); byte[] pendingBytes = Encoding.UTF8.GetBytes("true"); #pragma warning disable CS8601 // possible null reference assignment in the NSubstitute out-argument stub session.TryGetValue(HttpContextItemKeys.PENDING_SUPER_ADMIN_SETUP, out Arg.Any()).Returns(callInfo => @@ -70,7 +70,7 @@ public class LoginViewEndpointTests _mockUrlService.GetAbsoluteUrl(WebRoutes.Authentication.REGISTER_VIEW).Returns("http://localhost/en-us/auth/register"); // Act - IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_loginViewRequestFixture.Create(), CancellationToken.None); // Assert RedirectHttpResult redirectResult = Assert.IsType(result); @@ -85,7 +85,7 @@ public class LoginViewEndpointTests TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); // Act - IResult result = await _sut.ExecuteAsync(new LoginViewRequest(), CancellationToken.None); + IResult result = await _sut.ExecuteAsync(_loginViewRequestFixture.Create(), CancellationToken.None); // Assert Assert.IsType(result); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs index fad145e5..708e0b07 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/RecoverPassword/RecoverPasswordEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Web.Common.Responses.UsersManagement; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.RecoverPassword; using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using NSubstitute; @@ -26,6 +27,7 @@ public class RecoverPasswordEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly RecoverPasswordEndpoint _sut; private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + private readonly RecoverPasswordResponseFixture _recoverPasswordResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -41,7 +43,7 @@ public class RecoverPasswordEndpointTests { // Arrange RecoverPasswordRequest request = _recoverPasswordRequestFixture.Create(); - RecoverPasswordResponse expectedResponse = new(true); + RecoverPasswordResponse expectedResponse = _recoverPasswordResponseFixture.Create(isPasswordReset: true); _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(expectedResponse); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs index 7db86624..4284b3f0 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/UsersManagement/Authentication/Register/RegisterEndpointTests.cs @@ -6,6 +6,7 @@ using Lumina.Presentation.Web.Common.Responses.UsersManagement; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.UsersManagement.Authentication.Register; using Lumina.Presentation.Web.Fixtures.Common.Requests.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.Responses.UsersManagement; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using NSubstitute; @@ -26,6 +27,7 @@ public class RegisterEndpointTests private readonly IApiHttpClient _mockApiHttpClient; private readonly RegisterEndpoint _sut; private readonly RegisterRequestFixture _registerRequestFixture = new(); + private readonly RegisterResponseFixture _registerResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -42,7 +44,7 @@ public class RegisterEndpointTests // Arrange RegisterRequest request = _registerRequestFixture.Create(registrationType: "Admin"); _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new RegisterResponse(request.Username, null)); + .Returns(_registerResponseFixture.Create(username: request.Username)); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); @@ -63,7 +65,7 @@ public class RegisterEndpointTests // Arrange RegisterRequest request = _registerRequestFixture.Create(registrationType: "User"); _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new RegisterResponse(request.Username, null)); + .Returns(_registerResponseFixture.Create(username: request.Username)); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs index f8d7080d..11103814 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeLayoutRendererTests.cs @@ -11,7 +11,6 @@ using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; @@ -46,6 +45,9 @@ public class ThemeLayoutRendererTests private readonly IView _mockAudioPlayerView; private readonly IView _mockScriptsView; private readonly IView _mockNavMenuView; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); + private readonly ThemeLayoutPageDtoFixture _themeLayoutPageDtoFixture = new(); private readonly ThemeLayoutRenderer _sut; /// @@ -90,9 +92,9 @@ public class ThemeLayoutRendererTests { // Arrange _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: TestHttpContextFactory.CreateAuthenticatedUser())); - ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}"); - ThemeLayoutPageDto page = new("My Page", "
", ""); + ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "
", script: ""); // Act Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); @@ -107,9 +109,9 @@ public class ThemeLayoutRendererTests { // Arrange _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); - ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{assetBase}}|{{{appHead}}}|{{{nav}}}|{{{content}}}|{{{audioPlayer}}}|{{{appScripts}}}|{{{scripts}}}|{{mainStyle}}", navTemplate: "nav:{{siteName}}"); - ThemeLayoutPageDto page = new("My Page", "
", ""); + ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "
", script: ""); // Act Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); @@ -124,9 +126,9 @@ public class ThemeLayoutRendererTests { // Arrange _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); - ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); SetupRenderDocuments(theme, layoutTemplate: "{{title}}|{{{nav}}}", navTemplate: "{{#unclosed}}"); - ThemeLayoutPageDto page = new("My Page", "
", string.Empty); + ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "
", script: string.Empty); // Act Result result = await _sut.RenderAsync(page, "editorial", CancellationToken.None); @@ -142,9 +144,9 @@ public class ThemeLayoutRendererTests { // Arrange _mockHttpContextAccessor.HttpContext.Returns(TestHttpContextFactory.Create(user: null)); - ThemeResponseDto theme = new ThemeResponseDtoFixture().Create(themeId: "editorial"); + ThemeResponseDto theme = _themeResponseDtoFixture.Create(themeId: "editorial"); SetupRenderDocuments(theme, layoutTemplate: "{{title}}", navTemplate: "nav:{{siteName}}"); - ThemeLayoutPageDto page = new("My Page", "
", string.Empty); + ThemeLayoutPageDto page = _themeLayoutPageDtoFixture.Create(title: "My Page", content: "
", script: string.Empty); string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE .Replace("{themeId}", "editorial") .Replace("{*pageKey}", "shared/layout"); @@ -160,6 +162,12 @@ public class ThemeLayoutRendererTests await _mockApiHttpClient.Received(1).GetAsync(navEndpoint, Arg.Any()); } + /// + /// Stubs the API responses that return the layout and navigation menu templates of the given theme. + /// + /// The theme whose layout and navigation menu templates are stubbed. + /// The template returned for the layout document. + /// The template returned for the navigation menu document. private void SetupRenderDocuments(ThemeResponseDto theme, string layoutTemplate, string navTemplate) { string layoutEndpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE @@ -169,11 +177,16 @@ public class ThemeLayoutRendererTests .Replace("{themeId}", theme.ThemeId) .Replace("{*pageKey}", "shared/nav-menu"); _mockApiHttpClient.GetAsync(layoutEndpoint, Arg.Any()) - .Returns(new ThemeTemplateResponseDto(theme, layoutTemplate)); + .Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: layoutTemplate)); _mockApiHttpClient.GetAsync(navEndpoint, Arg.Any()) - .Returns(new ThemeTemplateResponseDto(theme, navTemplate)); + .Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: navTemplate)); } + /// + /// Creates a substitute view that renders the given markup. + /// + /// The markup rendered by the view. + /// The created substitute view. private static IView CreateView(string markup) { IView view = Substitute.For(); @@ -186,6 +199,10 @@ public class ThemeLayoutRendererTests return view; } + /// + /// Creates a substitute string localizer that returns a string prefixed with "Localized-". + /// + /// The created substitute string localizer. private static IStringLocalizer CreateLocalizer() { IStringLocalizer localizer = Substitute.For(); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs index cc4282f1..00a80d04 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemePageRendererTests.cs @@ -6,7 +6,6 @@ using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Themes; using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using NSubstitute; -using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; @@ -24,6 +23,7 @@ public class ThemePageRendererTests private readonly ThemePageRenderer _sut; private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); private readonly ThemePageDtoFixture _themePageDtoFixture = new(); + private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +46,7 @@ public class ThemePageRendererTests .Replace("{themeId}", "editorial-paper") .Replace("{*pageKey}", pageKey); _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) - .Returns(new ThemeTemplateResponseDto(theme, template)); + .Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: template)); ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); // Act @@ -74,7 +74,7 @@ public class ThemePageRendererTests _mockApiHttpClient.GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()) .Returns(currentTheme); _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) - .Returns(new ThemeTemplateResponseDto(currentTheme, "{{title}}")); + .Returns(_themeTemplateResponseDtoFixture.Create(theme: currentTheme, template: "{{title}}")); ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); // Act @@ -97,7 +97,7 @@ public class ThemePageRendererTests .Replace("{themeId}", "editorial-paper") .Replace("{*pageKey}", pageKey); _mockApiHttpClient.GetAsync(expectedEndpoint, Arg.Any()) - .Returns(new ThemeTemplateResponseDto(theme, "{{#unclosed}}")); + .Returns(_themeTemplateResponseDtoFixture.Create(theme: theme, template: "{{#unclosed}}")); ThemePageDto model = _themePageDtoFixture.Create(pageKey: pageKey, title: "Home"); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs index 0a306c3d..a14a38fb 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeServiceTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Enums.Themes; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.FileSystemManagement; using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; using NSubstitute; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -28,6 +27,7 @@ public class ThemeServiceTests private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); private readonly ThemeSettingsResponseDtoFixture _themeSettingsResponseDtoFixture = new(); private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); + private readonly BlobDataDtoFixture _blobDataDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -226,7 +226,7 @@ public class ThemeServiceTests string themeId = "editorial-paper"; byte[] data = [0x50, 0x4B, 0x03, 0x04]; _mockApiHttpClient.GetBlobAsync(Arg.Any(), Arg.Any()) - .Returns(new BlobDataDto { Data = data, ContentType = "application/zip" }); + .Returns(_blobDataDtoFixture.Create(data: data, contentType: "application/zip")); string expectedEndpoint = ApiRoutes.Themes.GET_THEME_ARCHIVE.Replace("{themeId}", themeId); // Act From 8144cb29863546b48b208d06464fe7617ab6c22c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 23:13:41 -0700 Subject: [PATCH 7/7] Uses platform path separator in artwork sanitization security test --- .../Artwork/BookArtworkServiceSecurityTests.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs index 05c0dbf8..de7bb94e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -124,12 +124,13 @@ public class BookArtworkServiceSecurityTests .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg")))); // Act + char separator = Path.DirectorySeparatorChar; Result result = await _sut.SaveBookArtworkAsync( Guid.NewGuid(), Guid.NewGuid(), - libraryName: "..\\..\\Library", - authorName: "..\\evil", - bookTitle: "..\\..\\cover", + libraryName: $"..{separator}..{separator}Library", + authorName: $"..{separator}evil", + bookTitle: $"..{separator}..{separator}cover", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);