diff --git a/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..8ae45f58 --- /dev/null +++ b/plugins/Lumina.Plugins.OpenLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,8 @@ +using System.Runtime.CompilerServices; + +// Test-enabling declaration for the Open Library plugin assembly. +// Mirrors the InternalsVisibleTo pattern present in every other testable source project, +// so that the internal Open Library types can be exercised by their unit tests. +[assembly: InternalsVisibleTo("Lumina.Plugins.OpenLibrary.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.OpenLibrary.Fixtures")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs index 1bede197..483bbccf 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandler.cs @@ -55,15 +55,15 @@ public class LibraryScanFailedDomainEventHandler : IDomainEventHandler getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( + Result getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync( domainEvent.MediaLibraryScanCompositeId.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScansResult.IsFailure) - throw new EventualConsistencyException(getLibraryScansResult.FirstError, getLibraryScansResult.Errors); - if (getLibraryScansResult.Value is null) + if (getLibraryScanResult.IsFailure) + throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); + if (getLibraryScanResult.Value is null) throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); // convert the repository scan to a domain object - Result libraryScanDomainResult = getLibraryScansResult.Value.ToDomainEntity(); + Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); if (libraryScanDomainResult.IsFailure) throw new EventualConsistencyException(libraryScanDomainResult.FirstError, libraryScanDomainResult.Errors); diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 4921de9d..301727f5 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -1,17 +1,15 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; 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; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Domain.Common.Errors; 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; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System.Threading; using System.Threading.Tasks; #endregion @@ -50,8 +48,10 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler getLibraryScanResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(domainEvent.ScanId.Value, cancellationToken).ConfigureAwait(false); - if (getLibraryScanResult.IsFailure || getLibraryScanResult.Value is null) + if (getLibraryScanResult.IsFailure) throw new EventualConsistencyException(getLibraryScanResult.FirstError, getLibraryScanResult.Errors); + if (getLibraryScanResult.Value is null) + throw new EventualConsistencyException(Errors.LibraryScanning.LibraryScanNotFound); // convert the repository entity to a domain entity Result libraryScanDomainResult = getLibraryScanResult.Value.ToDomainEntity(); diff --git a/src/Lumina.DataAccess/Common/Dapper/DapperTypeHandlers.cs b/src/Lumina.DataAccess/Common/Dapper/DapperTypeHandlers.cs new file mode 100644 index 00000000..805f03bd --- /dev/null +++ b/src/Lumina.DataAccess/Common/Dapper/DapperTypeHandlers.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using Dapper; +#endregion + +namespace Lumina.DataAccess.Common.Dapper; + +/// +/// Registers the Dapper type handlers used by the DataAccess layer. +/// +internal static class DapperTypeHandlers +{ + /// + /// Registers all Dapper type handlers used by the DataAccess layer, and must run before any Dapper query executes. + /// + internal static void Register() + { + SqlMapper.AddTypeHandler(new SqliteGuidTypeHandler()); + } +} diff --git a/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs new file mode 100644 index 00000000..63ac7047 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Dapper/SqliteGuidTypeHandler.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Dapper; +using System; +using System.Data; +#endregion + +namespace Lumina.DataAccess.Common.Dapper; + +/// +/// Maps values to and from the TEXT representation used by the SQLite provider. +/// +/// +/// The SQLite provider stores columns as TEXT, and Dapper falls back to Convert.ChangeType when materializing such +/// columns into properties. has no string , so that conversion throws +/// an ; this handler performs the conversion explicitly instead. +/// +internal sealed class SqliteGuidTypeHandler : SqlMapper.TypeHandler +{ + /// + /// Sets the parameter value to the TEXT representation of the value, keeping writes consistent with reads. + /// + /// The database parameter to set. + /// The value to store. + public override void SetValue(IDbDataParameter parameter, Guid value) + { + parameter.Value = value.ToString(); + } + + /// + /// Parses the raw TEXT value read from the storage medium into a . + /// + /// The raw value read from the storage medium. + /// The parsed . + public override Guid Parse(object value) + { + return value is Guid guid ? guid : Guid.Parse((string)value); + } +} diff --git a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs index fe87e21c..ea604dbf 100644 --- a/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs +++ b/src/Lumina.DataAccess/Common/DependencyInjection/DataAccessLayerServices.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Seed; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.DataAccess.Common.Dapper; using Lumina.DataAccess.Common.Interceptors; using Lumina.DataAccess.Core.Seed; using Lumina.DataAccess.Core.UoW; @@ -27,6 +28,9 @@ public static class DataAccessLayerServices /// The updated . public static void AddDataAccessLayerServices(this IServiceCollection services) { + // Type handlers are global static state, not DI services, and must be registered before any Dapper query executes; + // the composition root runs at startup, before any query, so this is the correct place for the application. + DapperTypeHandlers.Register(); string? basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!Directory.Exists(basePath)) throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist."); diff --git a/src/Lumina.sln b/src/Lumina.sln index 712b3786..4b86d8cb 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -232,6 +232,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.Int EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Presentation.Web.SecurityTests", "..\tests\SecurityTests\Lumina.Presentation.Web.SecurityTests\Lumina.Presentation.Web.SecurityTests.csproj", "{3FE25467-CBC6-438F-BB96-6601AF56E937}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Contracts.UnitTests", "..\tests\UnitTests\Lumina.Contracts.UnitTests\Lumina.Contracts.UnitTests.csproj", "{8336763E-26CE-4598-8438-26C7FFD60A2E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Domain.SharedKernel.UnitTests", "..\tests\UnitTests\Lumina.Domain.SharedKernel.UnitTests\Lumina.Domain.SharedKernel.UnitTests.csproj", "{B03AA3FE-4716-482C-8880-7BF3D9682A9F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Contracts.UnitTests", "..\tests\UnitTests\Lumina.Plugins.Contracts.UnitTests\Lumina.Plugins.Contracts.UnitTests.csproj", "{09F90296-A229-4CA2-8635-15B5893FE2EA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Contracts.Fixtures", "..\tests\Common\Lumina.Plugins.Contracts.Fixtures\Lumina.Plugins.Contracts.Fixtures.csproj", "{C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary.UnitTests", "..\tests\UnitTests\Lumina.Plugins.OpenLibrary.UnitTests\Lumina.Plugins.OpenLibrary.UnitTests.csproj", "{FEC00EBD-6A64-4280-B0F7-1EC5321C294A}" +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.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -574,6 +588,90 @@ Global {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x64.Build.0 = Release|Any CPU {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.ActiveCfg = Release|Any CPU {3FE25467-CBC6-438F-BB96-6601AF56E937}.Release|x86.Build.0 = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|x64.ActiveCfg = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|x64.Build.0 = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|x86.ActiveCfg = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Debug|x86.Build.0 = Debug|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|Any CPU.Build.0 = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|x64.ActiveCfg = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|x64.Build.0 = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|x86.ActiveCfg = Release|Any CPU + {8336763E-26CE-4598-8438-26C7FFD60A2E}.Release|x86.Build.0 = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|x64.ActiveCfg = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|x64.Build.0 = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|x86.ActiveCfg = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Debug|x86.Build.0 = Debug|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|Any CPU.Build.0 = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|x64.ActiveCfg = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|x64.Build.0 = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|x86.ActiveCfg = Release|Any CPU + {B03AA3FE-4716-482C-8880-7BF3D9682A9F}.Release|x86.Build.0 = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|x64.ActiveCfg = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|x64.Build.0 = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|x86.ActiveCfg = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Debug|x86.Build.0 = Debug|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|Any CPU.Build.0 = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|x64.ActiveCfg = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|x64.Build.0 = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|x86.ActiveCfg = Release|Any CPU + {09F90296-A229-4CA2-8635-15B5893FE2EA}.Release|x86.Build.0 = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|x64.ActiveCfg = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|x64.Build.0 = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|x86.ActiveCfg = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Debug|x86.Build.0 = Debug|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|Any CPU.Build.0 = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|x64.ActiveCfg = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|x64.Build.0 = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|x86.ActiveCfg = Release|Any CPU + {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB}.Release|x86.Build.0 = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|x64.ActiveCfg = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|x64.Build.0 = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|x86.ActiveCfg = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Debug|x86.Build.0 = Debug|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|Any CPU.Build.0 = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|x64.ActiveCfg = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|x64.Build.0 = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|x86.ActiveCfg = Release|Any CPU + {FEC00EBD-6A64-4280-B0F7-1EC5321C294A}.Release|x86.Build.0 = Release|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|x64.ActiveCfg = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|x64.Build.0 = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|x86.ActiveCfg = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Debug|x86.Build.0 = Debug|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|Any CPU.Build.0 = Release|Any CPU + {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x64.ActiveCfg = Release|Any CPU + {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 + {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 + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x64.Build.0 = Debug|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x86.ActiveCfg = Debug|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x86.Build.0 = Debug|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|Any CPU.Build.0 = Release|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|x64.ActiveCfg = Release|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|x64.Build.0 = Release|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|x86.ActiveCfg = Release|Any CPU + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -631,6 +729,13 @@ Global {697F6057-DBDC-40B9-A7E5-02F295BC18B3} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {4BE18EDC-02ED-47E2-A23A-3F6650ADAF0A} = {3F057926-562F-4EF4-BFC0-EE62372D4551} {3FE25467-CBC6-438F-BB96-6601AF56E937} = {8B06B1D2-80B9-490C-9A36-C7748F58B705} + {8336763E-26CE-4598-8438-26C7FFD60A2E} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {B03AA3FE-4716-482C-8880-7BF3D9682A9F} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {09F90296-A229-4CA2-8635-15B5893FE2EA} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {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} + {65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4A55A28E-C657-4A0B-95EA-2931AE66004E} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs new file mode 100644 index 00000000..334925bf --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/DirectoryScanFingerprintEntityFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class DirectoryScanFingerprintEntityFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the directory scan fingerprint. + /// Optional. The Id of the media library to which the fingerprint belongs. + /// Optional path of the directory to which the fingerprint belongs. + /// Optional last write time of the directory, in UTC. + /// A configured instance. + public DirectoryScanFingerprintEntity Create( + Guid? id = null, + Guid? libraryId = null, + string? path = null, + DateTime? lastWriteTimeUtc = null) + { + return new Faker() + .CustomInstantiator(faker => new DirectoryScanFingerprintEntity + { + Id = id ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid(), + Path = path ?? faker.System.DirectoryPath(), + LastWriteTimeUtc = lastWriteTimeUtc ?? faker.Date.Recent() + }) + .Generate(); + } + + /// + /// 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.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs new file mode 100644 index 00000000..605ca97f --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +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 LibraryEntityFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library. + /// Optional. The Id of the user that owns the media library. + /// Optional. The title of the media library. + /// Optional. The type of the media library. + /// Optional. The content locations of the media library. + /// 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 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. + public LibraryEntity Create( + Guid? id = null, + Guid? userId = null, + string? title = null, + LibraryType? libraryType = null, + IEnumerable? contentLocations = null, + string? coverImage = null, + bool isEnabled = true, + bool isLocked = false, + bool downloadMetadataFromWeb = true, + bool shouldSaveMetadataInMediaDirectories = true, + bool shouldSkipUnchangedDirectoriesDuringScan = false) + { + return new Faker() + .CustomInstantiator(f => new LibraryEntity + { + Id = id ?? Guid.NewGuid(), + UserId = userId ?? Guid.NewGuid(), + Title = default!, + CoverImage = default, + LibraryType = default, + ContentLocations = [], + LibraryScans = [], + IsEnabled = isEnabled, + IsLocked = isLocked, + DownloadMetadataFromWeb = downloadMetadataFromWeb, + ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories, + ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedOnUtc = null, + UpdatedBy = null + }) + .RuleFor(library => library.Title, f => title ?? f.Lorem.Word()) + .RuleFor(library => library.LibraryType, f => libraryType ?? f.PickRandom()) + .RuleFor(library => library.CoverImage, f => coverImage ?? f.System.FilePath()) + .RuleFor(library => library.ContentLocations, f => + { + IEnumerable paths = contentLocations ?? [f.System.DirectoryPath(), f.System.DirectoryPath()]; + return [.. paths.Select(path => new LibraryContentLocationEntity() { Path = path })]; + }) + .RuleFor(library => library.CreatedOnUtc, f => f.Date.Past()) + .RuleFor(library => library.CreatedBy, f => f.Random.Guid()) + .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/MediaLibrary/Management/LibraryScanEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntityFixture.cs new file mode 100644 index 00000000..5f9be4fd --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanEntityFixture.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +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 LibraryScanEntityFixture +{ + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library scan. + /// Optional. The Id of the media library that is scanned. + /// Optional. The Id of the user that initiated the media library scan. + /// The status of the media library scan. + /// Optional. The media library that is scanned. + /// Optional. The time and date when the entity was added. + /// The created media library scan entity. + public LibraryScanEntity Create( + Guid? id = null, + Guid? libraryId = null, + Guid? userId = null, + LibraryScanJobStatus? status = null, + LibraryEntity? libraryEntity = null, + DateTime? createdOnUtc = null) + { + Guid resolvedLibraryId = libraryId ?? Guid.NewGuid(); + Guid resolvedUserId = userId ?? Guid.NewGuid(); + LibraryEntity resolvedLibrary = libraryEntity ?? _libraryEntityFixture.Create(id: resolvedLibraryId, userId: resolvedUserId); + + return new Faker() + .CustomInstantiator(f => new LibraryScanEntity + { + Id = id ?? Guid.NewGuid(), + LibraryId = resolvedLibraryId, + UserId = resolvedUserId, + Status = status ?? LibraryScanJobStatus.Running, + Library = resolvedLibrary, + User = null!, + LibraryScanResults = [], + CreatedOnUtc = createdOnUtc ?? f.Date.Past(), + CreatedBy = resolvedUserId, + 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/MediaLibrary/Management/LibraryScanResultEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs new file mode 100644 index 00000000..5ce50582 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanResultEntityFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanResultEntityFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the media library scan result. + /// Optional. The Id of the media library scan that this result belongs to. + /// Optional status of the media library scan file. + /// Optional path of the media library scan file. + /// Optional hash calculated for the media library scan file. + /// Optional size of the media library scan file. + /// Optional last write time of the media library scan file, stored in ticks. + /// A configured instance. + public LibraryScanResultEntity Create( + Guid? id = null, + Guid? libraryScanId = null, + LibraryScanFileStatus? status = null, + string? path = null, + ulong? contentHash = null, + long? fileSize = null, + long? ticks = null) + { + return new Faker() + .CustomInstantiator(faker => new LibraryScanResultEntity + { + Id = id ?? Guid.NewGuid(), + LibraryScanId = libraryScanId ?? Guid.NewGuid(), + Status = status ?? faker.PickRandom(), + Path = path ?? faker.System.FilePath(), + ContentHash = contentHash ?? faker.Random.ULong(), + FileSize = fileSize ?? faker.Random.Long(1, long.MaxValue), + Ticks = ticks ?? faker.Random.Long(0, long.MaxValue), + LibraryScan = null! + }) + .Generate(); + } + + /// + /// 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.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs new file mode 100644 index 00000000..7ce61553 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanSnapshotEntityFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanSnapshotEntityFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the media library scan snapshot item. + /// Optional. The Id of the media library to which the snapshot item belongs. + /// Optional path of the media library scan snapshot item. + /// Optional hash calculated for the media library scan snapshot item. + /// Optional size of the media library scan snapshot item. + /// Optional last write time of the media library scan snapshot item, stored in ticks. + /// A configured instance. + public LibraryScanSnapshotEntity Create( + Guid? id = null, + Guid? libraryId = null, + string? path = null, + ulong? contentHash = null, + long? fileSize = null, + long? ticks = null) + { + return new Faker() + .CustomInstantiator(faker => new LibraryScanSnapshotEntity + { + Id = id ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid(), + Path = path ?? faker.System.FilePath(), + ContentHash = contentHash ?? faker.Random.ULong(), + FileSize = fileSize ?? faker.Random.Long(1, long.MaxValue), + Ticks = ticks ?? faker.Random.Long(0, long.MaxValue), + Library = null!, + CreatedOnUtc = faker.Date.Past(), + CreatedBy = Guid.NewGuid(), + UpdatedOnUtc = faker.Random.Bool() ? faker.Date.Recent() : null, + UpdatedBy = faker.Random.Bool() ? Guid.NewGuid() : null + }) + .Generate(); + } + + /// + /// 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.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs new file mode 100644 index 00000000..c1b8487a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryScanStagingResultsEntityFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanStagingResultsEntityFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The Id of the media library scan staging result. + /// Optional. The Id of the media library scan that this staging result belongs to. + /// Optional path of the media library scan staging result. + /// Optional size of the media library scan staging result. + /// Optional last write time of the file system item, stored in ticks. + /// Optional hash calculated for the media library scan staging result. + /// Optional hash stored in the media library scan snapshot of a previous scan. + /// Optional value indicating whether the file system item needs its content hashed. + /// Optional value indicating whether the file system item is new. + /// A configured instance. + public LibraryScanStagingResultsEntity Create( + Guid? id = null, + Guid? libraryScanId = null, + string? path = null, + long? size = null, + long? ticks = null, + ulong? contentHash = null, + ulong? previousContentHash = null, + bool? needsRehash = null, + bool? isNew = null) + { + return new Faker() + .CustomInstantiator(faker => new LibraryScanStagingResultsEntity + { + Id = id ?? Guid.NewGuid(), + LibraryScanId = libraryScanId ?? Guid.NewGuid(), + Path = path ?? faker.System.FilePath(), + Size = size ?? faker.Random.Long(1, long.MaxValue), + Ticks = ticks ?? faker.Random.Long(0, long.MaxValue), + ContentHash = contentHash ?? faker.Random.ULong(), + PreviousContentHash = previousContentHash ?? faker.Random.ULong(), + NeedsRehash = needsRehash ?? faker.Random.Bool(), + IsNew = isNew ?? faker.Random.Bool() + }) + .Generate(); + } + + /// + /// 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.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 3e5f2b6d..19c76868 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 @@ -23,18 +23,28 @@ public class BookEntityFixture /// /// Creates a random valid . /// + /// Optional. The Id of the book. + /// Optional. The Id of the media library that owns the book. + /// Optional. The file system path of the book. + /// Optional. The title of the book. + /// Optional. The original title of the book. /// The created . - public BookEntity Create() + public BookEntity Create( + Guid? id = null, + Guid? libraryId = null, + string? path = null, + string? title = null, + string? originalTitle = null) { int releaseYear = _random.Next(2000, 2010); int reReleaseYear = _random.Next(2010, 2020); return new Faker() - .RuleFor(x => x.Id, f => f.Random.Guid()) - .RuleFor(x => x.LibraryId, f => f.Random.Guid()) - .RuleFor(x => x.Path, f => f.System.FilePath()) - .RuleFor(x => x.Title, f => f.Random.String2(f.Random.Number(1, 255))) - .RuleFor(x => x.OriginalTitle, f => f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.Id, f => id ?? f.Random.Guid()) + .RuleFor(x => x.LibraryId, f => libraryId ?? f.Random.Guid()) + .RuleFor(x => x.Path, f => path ?? f.System.FilePath()) + .RuleFor(x => x.Title, f => title ?? f.Random.String2(f.Random.Number(1, 255))) + .RuleFor(x => x.OriginalTitle, f => originalTitle ?? f.Random.String2(f.Random.Number(1, 255))) .RuleFor(x => x.Description, f => f.Random.String2(f.Random.Number(1, 2000))) .RuleFor(x => x.OriginalReleaseDate, _faker.DateOnlyBetween(new DateOnly(releaseYear, 1, 1), new DateOnly(releaseYear, 12, 31))) .RuleFor(x => x.OriginalReleaseYear, releaseYear) 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 99b1b7d9..8fbb2def 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 @@ -21,8 +21,10 @@ public class UserEntityFixture /// Creates a random valid . /// /// 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. /// The created user entity. - public UserEntity Create(int libraryCount = 0) + public UserEntity Create(int libraryCount = 0, string? username = null, string? password = null) { Guid userId = Guid.NewGuid(); List libraries = libraryCount > 0 @@ -42,8 +44,8 @@ public class UserEntityFixture UserRole = null, CreatedBy = userId }) - .RuleFor(x => x.Username, f => f.Internet.UserName()) - .RuleFor(x => x.Password, f => Uri.EscapeDataString(f.Internet.Password())) + .RuleFor(x => x.Username, f => username ?? f.Internet.UserName()) + .RuleFor(x => x.Password, f => password ?? Uri.EscapeDataString(f.Internet.Password())) .RuleFor(x => x.CreatedOnUtc, f => f.Date.Past()) .RuleFor(x => x.TotpSecret, f => f.Random.Bool() ? f.Random.String2(32) : null) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/MediaLibraryScanJobPayloads/HashedFileSystemFileDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/MediaLibraryScanJobPayloads/HashedFileSystemFileDtoFixture.cs new file mode 100644 index 00000000..e12d4032 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/MediaLibraryScanJobPayloads/HashedFileSystemFileDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class HashedFileSystemFileDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The path of the file system file. + /// Optional. The size of the file system file. + /// Optional. The current hash obtained by sampling the file system file contents. + /// Optional. The old hash of the file system file, stored at the previous scan. + /// Optional. The time and date when the file system file was last modified, stored in ticks. + /// The created . + public HashedFileSystemFileDto Create( + string? path = null, + long? size = null, + ulong? currentHash = null, + ulong? oldHash = null, + long? ticks = null) + { + return new HashedFileSystemFileDto + { + Path = path ?? _faker.System.FilePath(), + Size = size ?? _faker.Random.Long(1, 1_000_000), + CurrentHash = currentHash ?? _faker.Random.ULong(), + OldHash = oldHash ?? _faker.Random.ULong(), + Ticks = ticks ?? _faker.Date.Recent().Ticks + }; + } + + /// + /// 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/Utilities/ValidatorUtilitiesTestEnum.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestEnum.cs new file mode 100644 index 00000000..3d008ba7 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestEnum.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +#endregion + +namespace Lumina.Application.Fixtures.Common.Utilities; + +/// +/// Enumeration used to exercise the extension method. +/// +public enum ValidatorUtilitiesTestEnum +{ + First, + Second +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs new file mode 100644 index 00000000..443bf52c --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequest.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.Fixtures.Common.Utilities; + +/// +/// Request used to exercise the extension methods. +/// +[ExcludeFromCodeCoverage] +public sealed record ValidatorUtilitiesTestRequest( + int IntValue, + int? NullableIntValue, + decimal DecimalValue, + decimal? NullableDecimalValue, + TimeSpan TimeSpanValue, + int IntValue2, + int? NullableIntValue2, + decimal? NullableDecimalValue2, + string? NotNullValue, + string? NotEmptyValue, + Guid NotEmptyGuidValue, + List? NotEmptyCollectionValue, + ValidatorUtilitiesTestEnum EnumValue, + ValidatorUtilitiesTestEnum? NullableEnumValue, + string? MaxLengthValue, + string? MinLengthValue, + string? ExactLengthValue, + string? RangeLengthValue, + string? MatchValue, + string? SelectorMatchValue, + string PatternValue, + int InclusiveIntValue, + int? InclusiveNullableIntValue, + string? EqualValue, + string? EqualComparisonValue); diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs new file mode 100644 index 00000000..22728308 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Utilities/ValidatorUtilitiesTestRequestFixture.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Utilities; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ValidatorUtilitiesTestRequestFixture +{ + private const string ValidPattern = "^[a-z]{3}-\\d{3}$"; + + /// + /// Creates a new instance with randomized test data that satisfies all validation rules. + /// + /// Optional. The integer value that must be greater than 3. + /// Optional. The nullable integer value that must be greater than 3. + /// Optional. The decimal value that must be greater than 3. + /// Optional. The nullable decimal value that must be greater than 3. + /// Optional. The time span value that must be greater than 3 hours. + /// Optional. The integer value that must be greater than or equal to 5. + /// Optional. The nullable integer value that must be greater than or equal to 5. + /// Optional. The nullable decimal value that must be greater than or equal to 5. + /// Optional. The value that must not be null. + /// Optional. The value that must not be empty. + /// Optional. The Guid that must not be empty. + /// Optional. The collection that must not be empty. + /// Optional. The enum value that must be defined. + /// Optional. The nullable enum value that must be defined. + /// Optional. The value that must not exceed 5 characters. + /// Optional. The value that must be at least 3 characters. + /// Optional. The value that must be exactly 3 characters. + /// Optional. The value that must be between 3 and 5 characters. + /// Optional. The value that must match the valid pattern. + /// Optional. The value that must match the pattern selected from the request. + /// Optional. The pattern the selector match value must match. + /// Optional. The integer value that must be between 1 and 10. + /// Optional. The nullable integer value that must be between 1 and 10. + /// Optional. The value that must equal the comparison value. + /// Optional. The comparison value. + /// A configured instance. + public ValidatorUtilitiesTestRequest Create( + int? intValue = null, + int? nullableIntValue = null, + decimal? decimalValue = null, + decimal? nullableDecimalValue = null, + TimeSpan? timeSpanValue = null, + int? intValue2 = null, + int? nullableIntValue2 = null, + decimal? nullableDecimalValue2 = null, + string? notNullValue = null, + string? notEmptyValue = null, + Guid? notEmptyGuidValue = null, + List? notEmptyCollectionValue = null, + ValidatorUtilitiesTestEnum? enumValue = null, + ValidatorUtilitiesTestEnum? nullableEnumValue = null, + string? maxLengthValue = null, + string? minLengthValue = null, + string? exactLengthValue = null, + string? rangeLengthValue = null, + string? matchValue = null, + string? selectorMatchValue = null, + string? patternValue = null, + int? inclusiveIntValue = null, + int? inclusiveNullableIntValue = null, + string? equalValue = null, + string? equalComparisonValue = null) + { + string resolvedPattern = patternValue ?? ValidPattern; + return new Faker() + .CustomInstantiator(f => new ValidatorUtilitiesTestRequest( + IntValue: intValue ?? f.Random.Int(4, 100), + NullableIntValue: nullableIntValue ?? f.Random.Int(4, 100), + DecimalValue: decimalValue ?? f.Random.Decimal(4m, 100m), + NullableDecimalValue: nullableDecimalValue ?? f.Random.Decimal(4m, 100m), + TimeSpanValue: timeSpanValue ?? f.Date.BetweenTimeOnly(new TimeOnly(4, 0), new TimeOnly(23, 0)).ToTimeSpan(), + IntValue2: intValue2 ?? f.Random.Int(5, 100), + NullableIntValue2: nullableIntValue2 ?? f.Random.Int(5, 100), + NullableDecimalValue2: nullableDecimalValue2 ?? f.Random.Decimal(5m, 100m), + NotNullValue: notNullValue ?? f.Lorem.Word(), + NotEmptyValue: notEmptyValue ?? f.Lorem.Word(), + NotEmptyGuidValue: notEmptyGuidValue ?? f.Random.Guid(), + NotEmptyCollectionValue: notEmptyCollectionValue ?? [f.Lorem.Word()], + EnumValue: enumValue ?? f.PickRandom(), + NullableEnumValue: nullableEnumValue ?? f.PickRandom(), + MaxLengthValue: maxLengthValue ?? f.Random.String2(1, 5), + MinLengthValue: minLengthValue ?? f.Random.String2(3, 5), + ExactLengthValue: exactLengthValue ?? f.Random.String2(3, 3), + RangeLengthValue: rangeLengthValue ?? f.Random.String2(3, 5), + MatchValue: matchValue ?? GenerateMatchingValue(f), + SelectorMatchValue: selectorMatchValue ?? GenerateMatchingValue(f), + PatternValue: resolvedPattern, + InclusiveIntValue: inclusiveIntValue ?? f.Random.Int(1, 10), + InclusiveNullableIntValue: inclusiveNullableIntValue ?? f.Random.Int(1, 10), + EqualValue: equalValue ?? "same", + EqualComparisonValue: equalComparisonValue ?? "same")) + .Generate(); + } + + /// + /// 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())]; + } + + private static string GenerateMatchingValue(Faker f) + { + string letters = new(Enumerable.Range(0, 3).Select(_ => f.Random.Char('a', 'z')).ToArray()); + return $"{letters}-{f.Random.Replace("###")}"; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryFixture.cs new file mode 100644 index 00000000..52e9481e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersQueryFixture +{ + /// + /// Creates a random valid query to get the metadata providers of a media library. + /// + /// Optional. The Id of the media library whose metadata providers are retrieved. + /// The created query. + public GetLibraryMetadataProvidersQuery Create(Guid? libraryId = null) + { + return new Faker() + .CustomInstantiator(f => new GetLibraryMetadataProvidersQuery( + 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.Application.Fixtures/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryFixture.cs new file mode 100644 index 00000000..061ad5dd --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsQueryFixture +{ + /// + /// Creates a random valid query to get the settings of a plugin. + /// + /// Optional. The unique identifier of the plugin. + /// The created query. + public GetPluginSettingsQuery Create(Guid? pluginId = null) + { + return new Faker() + .CustomInstantiator(f => new GetPluginSettingsQuery( + pluginId ?? 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/Authentication/PermissionDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Authentication/PermissionDtoFixture.cs new file mode 100644 index 00000000..64aebece --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Authentication/PermissionDtoFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Authentication; +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.DTO.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PermissionDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the permission. + /// Optional. The name of the permission. + /// The created . + public PermissionDto Create( + Guid? id = null, + AuthorizationPermission? permissionName = null) + { + return new PermissionDto( + id ?? Guid.NewGuid(), + permissionName ?? _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/DTO/Authentication/RoleDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Authentication/RoleDtoFixture.cs new file mode 100644 index 00000000..e3016e37 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Authentication/RoleDtoFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Authentication; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Authentication; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RoleDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the role. + /// Optional. The name of the role. + /// The created . + public RoleDto Create( + Guid? id = null, + string? roleName = null) + { + return new RoleDto( + id ?? Guid.NewGuid(), + roleName ?? _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/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs new file mode 100644 index 00000000..7fa9d6e3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoFixture.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BookMetadataDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// 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 name of the publisher of the book. + /// Optional. The number of pages in the book. + /// Whether optional properties should be included. + /// The created . + public BookMetadataDto Create( + string? title = null, + string? originalTitle = null, + string? description = null, + string? goodreadsId = null, + BookFormat? format = null, + string? publisher = null, + int? pageCount = null, + bool includeOptionalProperties = true) + { + int releaseYear = _faker.Random.Int(1900, 2024); + return new BookMetadataDto( + title ?? _faker.Lorem.Sentence(3), + 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, + publisher, + pageCount, + format ?? _faker.PickRandom(), + null, + includeOptionalProperties ? _faker.Random.Int(1, 10) : null, + null, + null, + goodreadsId, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + 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/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs new file mode 100644 index 00000000..f6af707b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BookMetadataLookupDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library the book belongs to. + /// Optional. The file system path of the book. + /// Optional. The ISBN of the book. + /// Optional. The Open Library ID of the book. + /// Optional. The title of the book. + /// Optional. The author of the book. + /// Optional. The language code of the book. + /// The created . + public BookMetadataLookupDto Create( + Guid? libraryId = null, + string? path = null, + string? isbn = null, + string? openLibraryId = null, + string? title = null, + string? author = null, + string? languageCode = null) + { + return new BookMetadataLookupDto( + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + isbn, + openLibraryId, + title, + author, + languageCode); + } + + /// + /// 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/UpdateRoleRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateRoleRequestFixture.cs new file mode 100644 index 00000000..009237cd --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateRoleRequestFixture.cs @@ -0,0 +1,48 @@ +#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 UpdateRoleRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the role to update. + /// Optional. The name of the role. + /// Optional. The Ids of the permissions of the role. + /// The created . + public UpdateRoleRequest Create( + Guid? roleId = null, + string? roleName = null, + List? permissions = null) + { + return new UpdateRoleRequest( + roleId ?? Guid.NewGuid(), + roleName ?? _faker.Random.Word(), + permissions ?? [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/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs new file mode 100644 index 00000000..893bb75c --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Authorization/UpdateUserRoleAndPermissionsRequestFixture.cs @@ -0,0 +1,48 @@ +#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 UpdateUserRoleAndPermissionsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user whose role and permissions are updated. + /// Optional. The Id of the role assigned to the user. + /// Optional. The Ids of the permissions assigned to the user. + /// The created . + public UpdateUserRoleAndPermissionsRequest Create( + Guid? userId = null, + Guid? roleId = null, + List? permissions = null) + { + return new UpdateUserRoleAndPermissionsRequest( + userId ?? Guid.NewGuid(), + roleId ?? Guid.NewGuid(), + permissions ?? [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/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs new file mode 100644 index 00000000..d297d071 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the media library. + /// Optional. The type of the media library. + /// Optional. The file system paths of the media library content directories. + /// 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 saved in the media directories. + /// Optional. Whether unchanged directories should be skipped during scan. + /// The created . + public AddLibraryRequest Create( + string? title = null, + string? libraryType = null, + string[]? contentLocations = null, + string? coverImage = null, + bool? isEnabled = null, + bool? isLocked = null, + bool? downloadMetadataFromWeb = null, + bool? shouldSaveMetadataInMediaDirectories = null, + bool? shouldSkipUnchangedDirectoriesDuringScan = null) + { + return new AddLibraryRequest( + title ?? _faker.Commerce.Department(), + libraryType ?? "EBook", + contentLocations ?? [_faker.System.DirectoryPath()], + coverImage ?? null, + isEnabled ?? _faker.Random.Bool(), + isLocked ?? _faker.Random.Bool(), + downloadMetadataFromWeb ?? _faker.Random.Bool(), + shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), + shouldSkipUnchangedDirectoriesDuringScan ?? _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/Requests/MediaLibrary/Management/CancelLibraryScanRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/CancelLibraryScanRequestFixture.cs new file mode 100644 index 00000000..d78685dc --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/CancelLibraryScanRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose scan is cancelled. + /// Optional. The Id of the scan to cancel. + /// The created . + public CancelLibraryScanRequest Create( + Guid? libraryId = null, + Guid? scanId = null) + { + return new CancelLibraryScanRequest( + libraryId ?? _faker.Random.Guid(), + scanId ?? _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/MediaLibrary/Management/DeleteLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/DeleteLibraryRequestFixture.cs new file mode 100644 index 00000000..703f224e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/DeleteLibraryRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to delete. + /// The created . + public DeleteLibraryRequest Create(Guid? id = null) + { + return new DeleteLibraryRequest( + id ?? _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/MediaLibrary/Management/GetLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryRequestFixture.cs new file mode 100644 index 00000000..f1ea27a2 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to retrieve. + /// The created . + public GetLibraryRequest Create(Guid? id = null) + { + return new GetLibraryRequest( + id ?? _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/MediaLibrary/Management/GetLibraryScanProgressRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestFixture.cs new file mode 100644 index 00000000..9ad24311 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose scan progress is requested. + /// Optional. The Id of the media library scan whose progress is requested. + /// The created . + public GetLibraryScanProgressRequest Create( + Guid? libraryId = null, + Guid? scanId = null) + { + return new GetLibraryScanProgressRequest( + libraryId ?? _faker.Random.Guid(), + scanId ?? _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/MediaLibrary/Management/ScanLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/ScanLibraryRequestFixture.cs new file mode 100644 index 00000000..0ab2e8b2 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/ScanLibraryRequestFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to scan. + /// The created . + public ScanLibraryRequest Create(Guid? id = null) + { + return new ScanLibraryRequest( + id ?? _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/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs new file mode 100644 index 00000000..ebdd308b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library to update. + /// Optional. The Id of the user owning the media library. + /// Optional. The title of the media library. + /// Optional. The type of the media library. + /// Optional. The file system paths of the media library content directories. + /// 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 saved in the media directories. + /// Optional. Whether unchanged directories should be skipped during scan. + /// The created . + public UpdateLibraryRequest Create( + Guid? id = null, + Guid? userId = null, + string? title = null, + string? libraryType = null, + string[]? contentLocations = null, + string? coverImage = null, + bool? isEnabled = null, + bool? isLocked = null, + bool? downloadMetadataFromWeb = null, + bool? shouldSaveMetadataInMediaDirectories = null, + bool? shouldSkipUnchangedDirectoriesDuringScan = null) + { + return new UpdateLibraryRequest( + id ?? _faker.Random.Guid(), + userId ?? _faker.Random.Guid(), + title ?? _faker.Commerce.Department(), + libraryType ?? "EBook", + contentLocations ?? [_faker.System.DirectoryPath()], + coverImage ?? null, + isEnabled ?? _faker.Random.Bool(), + isLocked ?? _faker.Random.Bool(), + downloadMetadataFromWeb ?? _faker.Random.Bool(), + shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), + shouldSkipUnchangedDirectoriesDuringScan ?? _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/Requests/Plugins/GetLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..e3731cc7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryMetadataProvidersRequestFixture.cs @@ -0,0 +1,41 @@ +#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 GetLibraryMetadataProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose metadata providers are retrieved. + /// The created . + public GetLibraryMetadataProvidersRequest Create(Guid? libraryId = null) + { + return new GetLibraryMetadataProvidersRequest( + 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/GetPluginSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetPluginSettingsRequestFixture.cs new file mode 100644 index 00000000..0fa2e81f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetPluginSettingsRequestFixture.cs @@ -0,0 +1,41 @@ +#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 GetPluginSettingsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin whose settings are retrieved. + /// The created . + public GetPluginSettingsRequest Create(Guid? pluginId = null) + { + return new GetPluginSettingsRequest( + pluginId ?? _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/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..a740a144 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.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 ReorderLibraryMetadataProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose metadata providers are reordered. + /// Optional. The plugin Ids in the new order. + /// The created . + public ReorderLibraryMetadataProvidersRequest Create( + Guid? libraryId = null, + IReadOnlyList? pluginIds = null) + { + return new ReorderLibraryMetadataProvidersRequest( + 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/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs new file mode 100644 index 00000000..2e47ed9c --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.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 SetLibraryMetadataProviderEnabledRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose metadata provider is enabled or disabled. + /// Optional. The Id of the plugin providing the metadata. + /// Optional. Whether the metadata provider should be enabled. + /// The created . + public SetLibraryMetadataProviderEnabledRequest Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool? isEnabled = null) + { + return new SetLibraryMetadataProviderEnabledRequest( + 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/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs new file mode 100644 index 00000000..921c81d1 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/UpdatePluginSettingsRequestFixture.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 UpdatePluginSettingsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin whose settings are updated. + /// Optional. The settings to apply to the plugin. + /// The created . + public UpdatePluginSettingsRequest Create( + Guid? pluginId = null, + IReadOnlyDictionary? settings = null) + { + return new UpdatePluginSettingsRequest( + pluginId ?? _faker.Random.Guid(), + settings ?? new Dictionary + { + [_faker.Lorem.Word()] = _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/Responses/Authentication/RegistrationResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RegistrationResponseFixture.cs new file mode 100644 index 00000000..04666560 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authentication/RegistrationResponseFixture.cs @@ -0,0 +1,48 @@ +#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 RegistrationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the registered user. + /// Optional. The username of the registered user. + /// Optional. The TOTP secret used for two-factor authentication. + /// The created . + public RegistrationResponse Create( + Guid? id = null, + string? username = null, + string? totpSecret = null) + { + return new RegistrationResponse( + id ?? Guid.NewGuid(), + username ?? _faker.Internet.UserName(), + totpSecret ?? _faker.Random.AlphaNumeric(16) + ); + } + + /// + /// 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/PermissionResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/PermissionResponseFixture.cs new file mode 100644 index 00000000..f4fde7c5 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/PermissionResponseFixture.cs @@ -0,0 +1,46 @@ +#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 PermissionResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the permission. + /// Optional. The name of the permission. + /// The created . + public PermissionResponse Create( + Guid? id = null, + AuthorizationPermission? permissionName = null) + { + return new PermissionResponse( + id ?? Guid.NewGuid(), + permissionName ?? _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/Authorization/RolePermissionsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RolePermissionsResponseFixture.cs new file mode 100644 index 00000000..be92090e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Authorization/RolePermissionsResponseFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.DTO.Authentication; +using Lumina.Contracts.Responses.Authorization; +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 RolePermissionsResponseFixture +{ + 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 RolePermissionsResponse Create( + RoleDto? role = null, + IEnumerable? permissions = null) + { + return new RolePermissionsResponse( + role ?? _roleDtoFixture.Create(), + (permissions ?? _permissionDtoFixture.CreateMany()).ToArray()); + } + + /// + /// 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 new file mode 100644 index 00000000..c3402218 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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 LibraryResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library. + /// Optional. The Id of the user owning the media library. + /// Optional. The title of the media library. + /// Optional. The type of the media library. + /// Optional. The file system paths of the media library content directories. + /// 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 saved in the media directories. + /// Optional. Whether unchanged directories should be skipped during scan. + /// Optional. The date and time when the library was created. + /// Optional. The date and time when the library was updated. + /// The created . + public LibraryResponse Create( + Guid? id = null, + Guid? userId = null, + string? title = null, + LibraryType? libraryType = null, + List? contentLocations = null, + string? coverImage = null, + bool? isEnabled = null, + bool? isLocked = null, + bool? downloadMetadataFromWeb = null, + bool? shouldSaveMetadataInMediaDirectories = null, + bool? shouldSkipUnchangedDirectoriesDuringScan = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null) + { + return new LibraryResponse( + id ?? Guid.NewGuid(), + userId ?? Guid.NewGuid(), + title ?? _faker.Commerce.Department(), + libraryType ?? _faker.PickRandom(), + contentLocations ?? [_faker.System.DirectoryPath(), _faker.System.DirectoryPath()], + coverImage, + isEnabled ?? _faker.Random.Bool(), + isLocked ?? _faker.Random.Bool(), + downloadMetadataFromWeb ?? _faker.Random.Bool(), + shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), + shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), + createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), + updatedOnUtc + ); + } + + /// + /// 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/MediaLibraryScanJobProgressResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseFixture.cs new file mode 100644 index 00000000..f38df439 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProgressResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The number of processed scan job items. + /// Optional. The total number of scan job items. + /// Optional. The current processing operation in the scan job. + /// Optional. The progress percentage of the scan job. + /// The created . + public MediaLibraryScanJobProgressResponse Create( + int? completedItems = null, + int? totalItems = null, + string? currentOperation = null, + decimal? progressPercentage = null) + { + return new MediaLibraryScanJobProgressResponse( + completedItems ?? _faker.Random.Int(0, 100), + totalItems ?? _faker.Random.Int(100, 1000), + currentOperation ?? _faker.Lorem.Word(), + progressPercentage ?? _faker.Random.Decimal(0m, 100m) + ); + } + + /// + /// 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/MediaLibraryScanProgressResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseFixture.cs new file mode 100644 index 00000000..4cf6a5d9 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +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 MediaLibraryScanProgressResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MediaLibraryScanJobProgressResponseFixture _mediaLibraryScanJobProgressResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library scan. + /// Optional. The Id of the user initiating the media library scan. + /// Optional. The Id of the media library that is scanned. + /// Optional. The total number of jobs to be processed by the scan. + /// Optional. The number of jobs that have been processed. + /// Optional. The progress of the currently processing job. + /// Optional. The status of the scan. + /// Optional. The overall progress percentage of the scan. + /// The created . + public MediaLibraryScanProgressResponse Create( + Guid? scanId = null, + Guid? userId = null, + Guid? libraryId = null, + int? totalJobs = null, + int? completedJobs = null, + MediaLibraryScanJobProgressResponse? currentJobProgress = null, + string? status = null, + decimal? overallProgressPercentage = null) + { + return new MediaLibraryScanProgressResponse( + scanId ?? Guid.NewGuid(), + userId ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid(), + totalJobs ?? _faker.Random.Int(1, 10), + completedJobs ?? _faker.Random.Int(0, 10), + currentJobProgress ?? _mediaLibraryScanJobProgressResponseFixture.Create(), + status ?? _faker.Lorem.Word(), + overallProgressPercentage ?? _faker.Random.Decimal(0m, 100m) + ); + } + + /// + /// 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/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs new file mode 100644 index 00000000..dd23ff53 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BookLiteResponseFixture +{ + 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. + /// The created . + public BookLiteResponse Create( + Guid? id = null, + string? title = null, + int? releaseYear = null, + string? coverPath = null) + { + return new BookLiteResponse( + id ?? Guid.NewGuid(), + title ?? _faker.Commerce.ProductName(), + releaseYear ?? _faker.Random.Int(1900, 2024), + coverPath ?? _faker.System.FilePath() + ); + } + + /// + /// 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/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs new file mode 100644 index 00000000..da74bf7d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseFixture.cs @@ -0,0 +1,102 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +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.Contracts.Responses.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 + +namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class BookResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the 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 metadata enrichment status of the book. + /// Optional. The date and time when the book was created. + /// The created . + public BookResponse Create( + Guid? id = null, + Guid? libraryId = null, + string? path = null, + WrittenContentMetadataDto? metadata = null, + BookFormat? format = null, + MetadataStatus? metadataStatus = null, + DateTime? createdOnUtc = null) + { + DateTime resolvedCreatedOnUtc = createdOnUtc ?? _faker.Date.Past().ToUniversalTime(); + return new BookResponse( + id ?? Guid.NewGuid(), + libraryId ?? Guid.NewGuid(), + path ?? _faker.System.FilePath(), + metadata ?? CreateMetadata(), + format ?? _faker.PickRandom(), + _faker.Lorem.Word(), + _faker.Random.Int(1, 10), + new BookSeriesDto(_faker.Lorem.Word()), + _faker.Random.AlphaNumeric(10), + _faker.Random.AlphaNumeric(5), + _faker.Random.AlphaNumeric(8), + _faker.Random.AlphaNumeric(10), + _faker.Random.AlphaNumeric(7), + _faker.Random.AlphaNumeric(7), + _faker.Random.AlphaNumeric(6), + _faker.Random.AlphaNumeric(10), + _faker.Random.AlphaNumeric(8), + [new IsbnDto(_faker.Random.Replace("###-#-##-#####-#"), IsbnFormat.Isbn13)], + [new MediaContributorDto( + new MediaContributorNameDto(_faker.Name.FullName(), _faker.Name.FullName()), + new MediaContributorRoleDto(_faker.Commerce.ProductAdjective(), _faker.Commerce.Department()))], + [new BookRatingDto(_faker.Random.Decimal(1m, 5m), 5m, BookRatingSource.Goodreads, _faker.Random.Int(1, 1000))], + metadataStatus ?? _faker.PickRandom(), + _faker.Date.Recent().ToUniversalTime(), + _faker.Company.CompanyName(), + resolvedCreatedOnUtc, + _faker.Random.Bool() ? _faker.Date.Recent().ToUniversalTime() : 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())]; + } + + private WrittenContentMetadataDto CreateMetadata() + { + return new WrittenContentMetadataDto( + _faker.Lorem.Sentence(3), + _faker.Lorem.Sentence(3), + _faker.Lorem.Paragraph(), + new ReleaseInfoDto(_faker.Date.PastDateOnly(), _faker.Random.Int(1900, 2024), null, null, _faker.Address.CountryCode(), null), + [new GenreDto(_faker.Lorem.Word())], + [new TagDto(_faker.Lorem.Word())], + new LanguageInfoDto("en", "English", "English"), + null, + _faker.Company.CompanyName(), + _faker.Random.Int(100, 1000) + ); + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs new file mode 100644 index 00000000..920ebac3 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginResponseFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.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 PluginResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin. + /// Optional. The display name of the plugin. + /// Optional. The author of the plugin. + /// Optional. The version of the plugin. + /// Optional. The description of the plugin. + /// Optional. The load status of the plugin. + /// Optional. The error message when the plugin failed to load. + /// Optional. The settings of the plugin. + /// The created . + public PluginResponse Create( + Guid? id = null, + string? name = null, + string? author = null, + string? version = null, + string? description = null, + PluginLoadStatus? loadStatus = null, + string? loadError = null, + IReadOnlyDictionary? settings = null) + { + return new PluginResponse( + id ?? Guid.NewGuid(), + name ?? _faker.Commerce.ProductName(), + author ?? _faker.Company.CompanyName(), + version ?? _faker.System.Semver(), + description ?? _faker.Lorem.Sentence(), + loadStatus ?? _faker.PickRandom(), + loadError, + settings ?? new Dictionary + { + [_faker.Lorem.Word()] = _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/Responses/Plugins/PluginSettingDescriptorResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginSettingDescriptorResponseFixture.cs new file mode 100644 index 00000000..de5b155d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginSettingDescriptorResponseFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +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 PluginSettingDescriptorResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The unique 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, when the setting is a selection. + /// The created . + public PluginSettingDescriptorResponse Create( + string? key = null, + string? label = null, + PluginSettingType? type = null, + string? defaultValue = null, + IReadOnlyList? allowedValues = null) + { + return new PluginSettingDescriptorResponse( + key ?? _faker.Lorem.Word(), + label ?? _faker.Lorem.Word(), + type ?? _faker.PickRandom(), + defaultValue, + allowedValues ?? [_faker.Lorem.Word(), _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/Responses/Plugins/PluginSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginSettingsResponseFixture.cs new file mode 100644 index 00000000..f41eb03b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/PluginSettingsResponseFixture.cs @@ -0,0 +1,52 @@ +#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 PluginSettingsResponseFixture +{ + private readonly Faker _faker = new(); + private readonly PluginSettingDescriptorResponseFixture _pluginSettingDescriptorResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin. + /// Optional. The schema of the plugin settings. + /// Optional. The current values of the plugin settings. + /// The created . + public PluginSettingsResponse Create( + Guid? pluginId = null, + IReadOnlyList? schema = null, + IReadOnlyDictionary? settings = null) + { + return new PluginSettingsResponse( + pluginId ?? Guid.NewGuid(), + schema ?? _pluginSettingDescriptorResponseFixture.CreateMany(3), + settings ?? new Dictionary + { + [_faker.Lorem.Word()] = _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/Responses/UsersManagement/Users/UserResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Users/UserResponseFixture.cs new file mode 100644 index 00000000..ebc53e5e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Users/UserResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement.Users; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Users; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UserResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user. + /// Optional. The username of the user. + /// Optional. The date and time when the user was created. + /// Optional. The date and time when the user was updated. + /// The created . + public UserResponse Create( + Guid? id = null, + string? username = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null) + { + return new UserResponse( + id ?? Guid.NewGuid(), + username ?? _faker.Internet.UserName(), + createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), + updatedOnUtc + ); + } + + /// + /// 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/Common/ValueObjects/Metadata/GenreFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/GenreFixture.cs new file mode 100644 index 00000000..3b5ce76e --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/GenreFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class GenreFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the genre. If not provided, a random name is generated. + /// The created . + public Genre Create(string? name = null) + { + Result genreResult = Genre.Create(name ?? _faker.Lorem.Word()); + + if (genreResult.IsFailure) + throw new InvalidOperationException("Failed to create Genre: " + string.Join(", ", genreResult.Errors)); + return genreResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs new file mode 100644 index 00000000..0a9640c7 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/LanguageInfoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The ISO 639-1 two-letter language code. If not provided, a random code is generated. + /// Optional. The full name of the language in English. If not provided, a random name is generated. + /// Optional. The native name of the language. If not provided, a random native name is generated. + /// The created . + public LanguageInfo Create( + string? languageCode = null, + string? languageName = null, + Optional? nativeName = null) + { + string[] languages = ["en", "es", "fr", "de", "it", "ja", "ko", "zh", "pt", "ru"]; + + Result languageInfoResult = LanguageInfo.Create( + languageCode ?? _faker.PickRandom(languages), + languageName ?? _faker.Lorem.Word(), + nativeName ?? Optional.Some(_faker.Lorem.Word())); + + if (languageInfoResult.IsFailure) + throw new InvalidOperationException("Failed to create LanguageInfo: " + string.Join(", ", languageInfoResult.Errors)); + return languageInfoResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs new file mode 100644 index 00000000..978e8d91 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/ReleaseInfoFixture.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoFixture +{ + private readonly Faker _faker = new(); + private readonly Random _random = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The original release date of the media item. + /// Optional. The original release year of the media item. + /// Optional. The re-release date of the media item. + /// Optional. The re-release year of the media item. + /// Optional. The country or region of release. + /// Optional. The release version or edition. + /// The created . + public ReleaseInfo Create( + Optional? originalReleaseDate = null, + Optional? originalReleaseYear = null, + Optional? reReleaseDate = null, + Optional? reReleaseYear = null, + Optional? releaseCountry = null, + Optional? releaseVersion = null) + { + int generatedYear = _random.Next(1900, 2000); + + Optional resolvedOriginalDate = originalReleaseDate ?? Optional.None(); + Optional resolvedOriginalYear = originalReleaseYear ?? Optional.None(); + if (!resolvedOriginalDate.HasValue && !resolvedOriginalYear.HasValue) + { + resolvedOriginalDate = Optional.Some(new DateOnly(generatedYear, 1, 1)); + resolvedOriginalYear = Optional.Some(generatedYear); + } + else if (!resolvedOriginalDate.HasValue) + { + resolvedOriginalDate = Optional.Some(new DateOnly(resolvedOriginalYear.Value, 1, 1)); + } + else if (!resolvedOriginalYear.HasValue) + { + resolvedOriginalYear = Optional.Some(resolvedOriginalDate.Value.Year); + } + + Optional resolvedReReleaseDate = reReleaseDate ?? Optional.None(); + Optional resolvedReReleaseYear = reReleaseYear ?? Optional.None(); + if (resolvedReReleaseDate.HasValue && !resolvedReReleaseYear.HasValue) + { + resolvedReReleaseYear = Optional.Some(resolvedReReleaseDate.Value.Year); + } + else if (!resolvedReReleaseDate.HasValue && resolvedReReleaseYear.HasValue) + { + resolvedReReleaseDate = Optional.Some(new DateOnly(resolvedReReleaseYear.Value, 1, 1)); + } + + Result releaseInfoResult = ReleaseInfo.Create( + resolvedOriginalDate, + resolvedOriginalYear, + resolvedReReleaseDate, + resolvedReReleaseYear, + releaseCountry ?? Optional.Some(_faker.Address.Country()), + releaseVersion ?? Optional.Some(_faker.Lorem.Word())); + + if (releaseInfoResult.IsFailure) + throw new InvalidOperationException("Failed to create ReleaseInfo: " + string.Join(", ", releaseInfoResult.Errors)); + return releaseInfoResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/TagFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/TagFixture.cs new file mode 100644 index 00000000..43b9f491 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Common/ValueObjects/Metadata/TagFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class TagFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the tag. If not provided, a random name is generated. + /// The created . + public Tag Create(string? name = null) + { + Result tagResult = Tag.Create(name ?? _faker.Lorem.Word()); + + if (tagResult.IsFailure) + throw new InvalidOperationException("Failed to create Tag: " + string.Join(", ", tagResult.Errors)); + return tagResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataFixture.cs new file mode 100644 index 00000000..d53ab8bc --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataFixture.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class AudioMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the audio. + /// Optional. The original title of the audio. + /// Optional. The duration of the audio, in seconds. + /// Optional. The sample rate of the audio, in Hz. + /// Optional. The number of audio channels. + /// Optional. The release information of the audio. + /// Optional. The description of the audio. + /// Optional. The genres of the audio. + /// Optional. The tags associated with the audio. + /// Optional. The language of the audio. + /// Optional. The original language of the audio. + /// Optional. The bit depth of the audio. + /// Optional. The audio codec used. + /// Optional. The bitrate of the audio, in kbps. + /// The created . + public AudioMetadata Create( + string? title = null, + Optional? originalTitle = null, + int? durationInSeconds = null, + int? sampleRate = null, + int? channels = null, + ReleaseInfo? releaseInfo = null, + Optional? description = null, + List? genres = null, + List? tags = null, + Optional? language = null, + Optional? originalLanguage = null, + Optional? bitDepth = null, + Optional? audioCodec = null, + Optional? bitrate = null) + { + return AudioMetadata.Create( + title ?? _faker.Music.Genre(), + originalTitle ?? Optional.None(), + durationInSeconds ?? _faker.Random.Int(60, 7200), + sampleRate ?? _faker.Random.Int(44100, 192000), + channels ?? _faker.Random.Int(1, 8), + releaseInfo ?? _releaseInfoFixture.Create(), + description ?? Optional.Some(_faker.Lorem.Sentence()), + genres ?? [_genreFixture.Create(), _genreFixture.Create()], + tags ?? [_tagFixture.Create(), _tagFixture.Create()], + language ?? Optional.Some(_languageInfoFixture.Create()), + originalLanguage ?? Optional.None(), + bitDepth ?? Optional.Some(_faker.Random.Int(8, 32)), + audioCodec ?? Optional.Some("PCM"), + bitrate ?? Optional.Some(_faker.Random.Int(128, 320))).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} 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 b9ab4b10..c438f06b 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 @@ -32,6 +32,7 @@ public class LibraryFixture /// Optional. The library type. /// Optional. The content locations of the library. /// Optional. The cover image of the library. + /// 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. @@ -46,6 +47,7 @@ public class LibraryFixture LibraryType? libraryType = null, IEnumerable? contentLocations = null, string? coverImage = null, + bool includeCoverImage = true, bool isEnabled = true, bool isLocked = false, bool downloadMetadataFromWeb = true, @@ -62,6 +64,7 @@ public class LibraryFixture ]; List resolvedScanIds = scanIds is null ? [ScanId.CreateUnique(), ScanId.CreateUnique()] : [.. scanIds.Select(scanId => ScanId.Create(scanId))]; + string? resolvedCoverImage = includeCoverImage ? (coverImage ?? _faker.System.FilePath()) : null; Result library = id is null ? Library.Create( @@ -69,7 +72,7 @@ public class LibraryFixture title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), - coverImage ?? _faker.System.FilePath(), + resolvedCoverImage, isEnabled, isLocked, downloadMetadataFromWeb, @@ -83,7 +86,7 @@ public class LibraryFixture title ?? _faker.Random.String2(_faker.Random.Number(1, 50)), libraryType ?? _faker.PickRandom(), contentLocations ?? validPaths.Take(_random.Next(1, validPaths.Count)), - coverImage ?? _faker.System.FilePath(), + resolvedCoverImage, isEnabled, isLocked, downloadMetadataFromWeb, diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryIdFixture.cs new file mode 100644 index 00000000..ef83dd0c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/ValueObjects/LibraryIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class LibraryIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the library Id. + /// The created . + public LibraryId Create(Guid? value = null) + { + return LibraryId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanFixture.cs new file mode 100644 index 00000000..7c495ce8 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +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.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFixture +{ + /// + /// Creates a random valid domain aggregate. + /// + /// Optional. The scan Id. + /// Optional. The Id of the media library that is scanned. + /// Optional. The Id of the user that initiated the scan. + /// Optional. The status of the media library scan. + /// Optional. The list of past scans of the scanned media library. + /// The created . + public LibraryScan Create( + Guid? id = null, + Guid? libraryId = null, + Guid? userId = null, + LibraryScanJobStatus? status = null, + List? pastScans = null) + { + Result scan = LibraryScan.Create( + ScanId.Create(id ?? Guid.NewGuid()), + LibraryId.Create(libraryId ?? Guid.NewGuid()), + UserId.Create(userId ?? Guid.NewGuid()), + status ?? LibraryScanJobStatus.Pending, + pastScans ?? []); + + return scan.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdFixture.cs new file mode 100644 index 00000000..b0f25084 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanCompositeIdFixture +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The scan Id of the composite scan identifier. + /// Optional. The user Id of the composite scan identifier. + /// The created . + public MediaLibraryScanCompositeId Create(ScanId? scanId = null, UserId? userId = null) + { + return MediaLibraryScanCompositeId.Create( + scanId ?? _scanIdFixture.Create(), + userId ?? _userIdFixture.Create()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressFixture.cs new file mode 100644 index 00000000..90209063 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProgressFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The number of completed items of the scan job. + /// Optional. The total number of items of the scan job. + /// Optional. The current operation being performed by the scan job. + /// The created . + public MediaLibraryScanJobProgress Create( + int? completedItems = null, + int? totalItems = null, + string? currentOperation = null) + { + Result progress = MediaLibraryScanJobProgress.Create( + completedItems ?? _faker.Random.Number(0, 100), + totalItems ?? _faker.Random.Number(100, 200), + currentOperation ?? _faker.Random.Words()); + + return progress.Value; + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressFixture.cs new file mode 100644 index 00000000..38fe403a --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +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.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProgressFixture +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The scan Id of the media library scan. + /// Optional. The user Id of the user initiating the media library scan. + /// Optional. The library Id of the scanned media library. + /// Optional. The number of completed jobs of the media library scan. + /// Optional. The total number of jobs of the media library scan. + /// Optional. The status of the media library scan. + /// Optional. The current job progress of the media library scan. When , no current job progress is set. + /// The created . + public MediaLibraryScanProgress Create( + ScanId? scanId = null, + UserId? userId = null, + LibraryId? libraryId = null, + int? completedJobs = null, + int? totalJobs = null, + LibraryScanJobStatus? status = null, + Optional? currentJobProgress = null) + { + Result progress = MediaLibraryScanProgress.Create( + scanId ?? _scanIdFixture.Create(), + userId ?? _userIdFixture.Create(), + libraryId ?? _libraryIdFixture.Create(), + completedJobs ?? 1, + totalJobs ?? 2, + status ?? LibraryScanJobStatus.Pending, + currentJobProgress ?? Optional.None()); + + return progress.Value; + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdFixture.cs new file mode 100644 index 00000000..49f37181 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class ScanIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the scan Id. + /// The created . + public ScanId Create(Guid? value = null) + { + return ScanId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdFixture.cs new file mode 100644 index 00000000..92b74f8c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public MediaContributorId Create(Guid? value = null) + { + return value is null ? MediaContributorId.CreateUnique() : MediaContributorId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameFixture.cs new file mode 100644 index 00000000..f251c806 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name by which the contributor is popularly known. If not provided, a random name is generated. + /// Optional. The legal name of the contributor. If not provided, a random legal name is generated. + /// The created . + public MediaContributorName Create(string? displayName = null, Optional? legalName = null) + { + Result nameResult = MediaContributorName.Create( + displayName ?? _faker.Person.FullName, + legalName ?? Optional.Some(_faker.Person.FullName)); + + if (nameResult.IsFailure) + throw new InvalidOperationException("Failed to create MediaContributorName: " + string.Join(", ", nameResult.Errors)); + return nameResult.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs new file mode 100644 index 00000000..74ba2906 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRoleFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the role. If not provided, a random name is generated. + /// Optional. The category of the role. If not provided, a random category is generated. + /// The created . + public MediaContributorRole Create(string? name = null, string? category = null) + { + return MediaContributorRole.Create( + name ?? _faker.Lorem.Word(), + category ?? _faker.Commerce.Department()); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserFixture.cs new file mode 100644 index 00000000..7851bc5d --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserFixture.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class UserFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid domain aggregate. + /// + /// Optional. The user Id. + /// Optional. The username of the user. + /// The created . + public User Create(Guid? id = null, string? username = null) + { + UserId userId = id is null ? UserId.CreateUnique() : UserId.Create(id.Value); + Result user = User.Create(userId, username ?? _faker.Internet.UserName()); + return user.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserIdFixture.cs new file mode 100644 index 00000000..7189a5c6 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/ValueObjects/UserIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class UserIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the user Id. + /// The created . + public UserId Create(Guid? value = null) + { + return UserId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs new file mode 100644 index 00000000..dc4ffd36 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsFixture +{ + /// + /// Creates a random valid domain aggregate. + /// + /// 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. + /// The created . + public UserSettings Create( + Guid? userId = null, + bool isPaginationEnabled = true, + int itemsPerPage = 48, + bool ignoreThePrefixForAlphaPicker = false) + { + Result settings = UserSettings.Create( + userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value), + isPaginationEnabled, + itemsPerPage, + ignoreThePrefixForAlphaPicker); + return settings.Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieFixture.cs new file mode 100644 index 00000000..32b9d47c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class MovieFixture +{ + private readonly VideoMetadataFixture _videoMetadataFixture = new(); + private readonly MovieIdFixture _movieIdFixture = new(); + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the movie. + /// Optional. The metadata of the movie. + /// Optional. The list of media contributors of the movie. + /// Optional. The list of ratings for the movie. + /// The created . + public Movie Create( + MovieId? id = null, + VideoMetadata? metadata = null, + List? contributors = null, + List? ratings = null) + { + return Movie.Create( + id ?? _movieIdFixture.Create(), + metadata ?? _videoMetadataFixture.Create(), + contributors ?? [_mediaContributorIdFixture.Create()], + ratings ?? []).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdFixture.cs new file mode 100644 index 00000000..c7784f66 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class MovieIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public MovieId Create(Guid? value = null) + { + return value is null ? MovieId.CreateUnique() : MovieId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataFixture.cs new file mode 100644 index 00000000..c38c2638 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataFixture.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class VideoMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the video. + /// Optional. The original title of the video. + /// Optional. The duration of the video in seconds. + /// Optional. The resolution of the video. + /// Optional. The description of the video. + /// Optional. The release information of the video. + /// Optional. The language of the video. + /// Optional. The original language of the video. + /// Optional. The frame rate of the video. + /// Optional. The video codec used. + /// Optional. The audio codec used. + /// Optional. The genres of the video. + /// Optional. The tags associated with the video. + /// The created . + public VideoMetadata Create( + string? title = null, + Optional? originalTitle = null, + int? durationInSeconds = null, + string? resolution = null, + Optional? description = null, + ReleaseInfo? releaseInfo = null, + Optional? language = null, + Optional? originalLanguage = null, + Optional? frameRate = null, + Optional? videoCodec = null, + Optional? audioCodec = null, + List? genres = null, + List? tags = null) + { + return VideoMetadata.Create( + title ?? _faker.Commerce.ProductName(), + originalTitle ?? Optional.None(), + durationInSeconds ?? _faker.Random.Int(60, 18000), + resolution ?? "1920x1080", + description ?? Optional.Some(_faker.Lorem.Sentence()), + releaseInfo ?? _releaseInfoFixture.Create(), + language ?? Optional.Some(_languageInfoFixture.Create()), + originalLanguage ?? Optional.None(), + frameRate ?? Optional.Some(24), + videoCodec ?? Optional.Some("H.264"), + audioCodec ?? Optional.Some("AAC"), + genres ?? [_genreFixture.Create(), _genreFixture.Create()], + tags ?? [_tagFixture.Create(), _tagFixture.Create()]).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdFixture.cs new file mode 100644 index 00000000..7db68763 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class EpisodeIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public EpisodeId Create(Guid? value = null) + { + return value is null ? EpisodeId.CreateUnique() : EpisodeId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdFixture.cs new file mode 100644 index 00000000..83ac3efd --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class SeasonIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public SeasonId Create(Guid? value = null) + { + return value is null ? SeasonId.CreateUnique() : SeasonId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdFixture.cs new file mode 100644 index 00000000..147bdaff --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class TvShowIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public TvShowId Create(Guid? value = null) + { + return value is null ? TvShowId.CreateUnique() : TvShowId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookSeriesFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookSeriesFixture.cs new file mode 100644 index 00000000..24c3b227 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/BookSeriesFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesFixture +{ + private readonly BookSeriesIdFixture _bookSeriesIdFixture = new(); + private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The unique identifier of the book series. + /// Whether the book series is complete. + /// The created . + public BookSeries Create( + Guid? id = null, + bool isComplete = false) + { + return BookSeries.Create( + id is null ? BookSeriesId.CreateUnique() : _bookSeriesIdFixture.Create(id.Value), + _writtenContentMetadataFixture.Create(), + isComplete, + []).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdFixture.cs new file mode 100644 index 00000000..12b20431 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class BookIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public BookId Create(Guid? value = null) + { + return value is null ? BookId.CreateUnique() : BookId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs new file mode 100644 index 00000000..e8293a8b --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class BookLibraryIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public BookLibraryId Create(Guid? value = null) + { + return value is null ? BookLibraryId.CreateUnique().Value : BookLibraryId.Create(value.Value).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdFixture.cs new file mode 100644 index 00000000..7458ff82 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The value used to create the . If not provided, a random value is generated. + /// The created . + public BookSeriesId Create(Guid? value = null) + { + return value is null ? BookSeriesId.CreateUnique() : BookSeriesId.Create(value.Value); + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs index eb0117f8..674e4d1b 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnFixture.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; @@ -19,13 +20,23 @@ public class IsbnFixture /// /// Creates a valid with a random or explicitly requested format. /// + /// Optional. The ISBN value to use. If not provided, a random valid value is generated for the requested format. /// Optional. The requested . If not provided, a random format is selected. /// The created . - public Isbn Create(IsbnFormat? format = null) + public Isbn Create(string? value = null, IsbnFormat? format = null) { - IsbnFormat targetFormat = format ?? (_random.Next(2) == 0 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); - string isbn = targetFormat == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13(); - return Isbn.Create(isbn, targetFormat).Value; + if (value is not null) + { + IsbnFormat targetFormat = format ?? IsbnFormat.Isbn10; + Result result = Isbn.Create(value, targetFormat); + if (result.IsFailure) + throw new InvalidOperationException("Failed to create Isbn: " + string.Join(", ", result.Errors)); + return result.Value; + } + + IsbnFormat requestedFormat = format ?? (_random.Next(2) == 0 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13); + string isbn = requestedFormat == IsbnFormat.Isbn10 ? GenerateValidIsbn10() : GenerateValidIsbn13(); + return Isbn.Create(isbn, requestedFormat).Value; } /// diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataFixture.cs new file mode 100644 index 00000000..c752d611 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataFixture.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Fixture class for the domain value object. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataFixture +{ + private readonly Faker _faker = new(); + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The title of the written content. + /// Optional. The original title of the written content. + /// Optional. The description of the written content. + /// Optional. The release information of the written content. + /// Optional. The genres of the written content. + /// Optional. The tags associated with the written content. + /// Optional. The language of the written content. + /// Optional. The original language of the written content. + /// Optional. The publisher of the written content. + /// Optional. The number of pages in the written content. + /// The created . + public WrittenContentMetadata Create( + string? title = null, + Optional? originalTitle = null, + Optional? description = null, + ReleaseInfo? releaseInfo = null, + List? genres = null, + List? tags = null, + Optional? language = null, + Optional? originalLanguage = null, + Optional? publisher = null, + Optional? pageCount = null) + { + return WrittenContentMetadata.Create( + title ?? _faker.Commerce.ProductName(), + originalTitle ?? Optional.None(), + description ?? Optional.Some(_faker.Lorem.Sentence()), + releaseInfo ?? _releaseInfoFixture.Create(), + genres ?? [_genreFixture.Create(), _genreFixture.Create()], + tags ?? [_tagFixture.Create(), _tagFixture.Create()], + language ?? Optional.Some(_languageInfoFixture.Create()), + originalLanguage ?? Optional.None(), + publisher ?? Optional.Some(_faker.Company.CompanyName()), + pageCount ?? Optional.Some(_faker.Random.Int(1, 1000))).Value; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/CorsSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/CorsSettingsDtoFixture.cs new file mode 100644 index 00000000..ad7f92be --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/CorsSettingsDtoFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class CorsSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a valid . + /// + /// Optional. The allowed origins, or to generate valid origins. + /// The created . + public CorsSettingsDto Create(string[]? allowedOrigins = null) + { + return new CorsSettingsDto + { + AllowedOrigins = allowedOrigins ?? [$"https://{_faker.Internet.DomainName()}", $"http://{_faker.Internet.DomainName()}"] + }; + } + + /// + /// 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.Infrastructure.Fixtures/Common/Models/DTO/Configuration/PluginsSettingsDtoFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/PluginsSettingsDtoFixture.cs new file mode 100644 index 00000000..0405fb9a --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Models/DTO/Configuration/PluginsSettingsDtoFixture.cs @@ -0,0 +1,41 @@ +#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.Infrastructure.Fixtures.Common.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a valid . + /// + /// Optional. The directory where the plugin assemblies are located. + /// The created . + public PluginsSettingsDto Create(string? directory = null) + { + return new PluginsSettingsDto + { + Directory = directory ?? _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.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs index 4e351ce4..af851c44 100644 --- a/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Core/Authorization/AuthorizationServiceFixture.cs @@ -22,7 +22,7 @@ public class AuthorizationServiceFixture /// Direct permissions to assign to the user. /// Permissions to assign through roles. /// The created user entity. - public static UserEntity CreateUserWithPermissions( + public UserEntity CreateUserWithPermissions( IEnumerable? directPermissions = null, Dictionary>? rolePermissions = null) { diff --git a/tests/Common/Lumina.Plugins.Contracts.Fixtures/Common/Models/DTO/Settings/PluginSettingDescriptorDtoFixture.cs b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Common/Models/DTO/Settings/PluginSettingDescriptorDtoFixture.cs new file mode 100644 index 00000000..f225416c --- /dev/null +++ b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Common/Models/DTO/Settings/PluginSettingDescriptorDtoFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the record. +/// +[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 ?? _faker.Random.String2(4, 32), + label ?? _faker.Commerce.ProductName(), + type ?? _faker.Random.Enum(), + defaultValue, + 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.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj new file mode 100644 index 00000000..ae4a178e --- /dev/null +++ b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Lumina.Plugins.Contracts.Fixtures.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.Contracts.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Contracts.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..421b3ab6 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Contracts.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.Contracts.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.Contracts.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("A1B2C3D4-0001-4A5B-9C0D-111111111111")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.Contracts.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryAuthorResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryAuthorResponseFixture.cs new file mode 100644 index 00000000..3e790199 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryAuthorResponseFixture.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryAuthorResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the author. + /// Optional. The name of the author. + /// Optional. The personal name of the author. + /// The created author response. + public OpenLibraryAuthorResponse Create( + string? key = null, + string? name = null, + string? personalName = null) + { + return new OpenLibraryAuthorResponse + { + Key = key ?? $"/authors/OL{_faker.Random.Number(1000, 9999)}A", + Name = name ?? _faker.Name.FullName(), + PersonalName = personalName + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryEditionResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryEditionResponseFixture.cs new file mode 100644 index 00000000..cf3b10eb --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryEditionResponseFixture.cs @@ -0,0 +1,95 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryEditionResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the edition. + /// Optional. The title of the edition. + /// Optional. The subtitle of the edition. + /// Optional. The notes of the edition. + /// Optional. The publication date of the edition. + /// Optional. The publishers of the edition. + /// Optional. The publication places of the edition. + /// Optional. The number of pages of the edition. + /// Optional. The physical format of the edition. + /// Optional. The name of the edition. + /// Optional. The series of the edition. + /// Optional. The volume of the edition within its series. + /// Optional. The ISBN-10 identifiers of the edition. + /// Optional. The ISBN-13 identifiers of the edition. + /// Optional. The LCCN identifiers of the edition. + /// Optional. The OCLC numbers of the edition. + /// Optional. The external identifiers of the edition. + /// Optional. The source records of the edition. + /// Optional. The languages of the edition. + /// Optional. The authors of the edition. + /// Optional. The works the edition belongs to. + /// Optional. The contributions of the edition. + /// The created edition response. + public OpenLibraryEditionResponse Create( + string? key = null, + string? title = null, + string? subtitle = null, + JsonElement? notes = null, + string? publishDate = null, + List? publishers = null, + List? publishPlaces = null, + int? numberOfPages = null, + string? physicalFormat = null, + string? editionName = null, + List? series = null, + string? volume = null, + List? isbn10 = null, + List? isbn13 = null, + List? lccn = null, + List? oclcNumbers = null, + JsonElement? identifiers = null, + List? sourceRecords = null, + List? languages = null, + List? authors = null, + List? works = null, + List? contributions = null) + { + return new OpenLibraryEditionResponse + { + Key = key ?? $"/books/OL{_faker.Random.Number(1000, 9999)}M", + Title = title ?? _faker.Commerce.ProductName(), + Subtitle = subtitle, + Notes = notes ?? default, + PublishDate = publishDate, + Publishers = publishers ?? [], + PublishPlaces = publishPlaces ?? [], + NumberOfPages = numberOfPages, + PhysicalFormat = physicalFormat, + EditionName = editionName, + Series = series ?? [], + Volume = volume, + Isbn10 = isbn10 ?? [], + Isbn13 = isbn13 ?? [], + Lccn = lccn ?? [], + OclcNumbers = oclcNumbers ?? [], + Identifiers = identifiers ?? default, + SourceRecords = sourceRecords ?? [], + Languages = languages ?? [], + Authors = authors ?? [], + Works = works ?? [], + Contributions = contributions ?? [] + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponseFixture.cs new file mode 100644 index 00000000..34f05e58 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryKeyReferenceResponseFixture.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryKeyReferenceResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the referenced resource. + /// The created reference response. + public OpenLibraryKeyReferenceResponse Create(string? key = null) + { + return new OpenLibraryKeyReferenceResponse + { + Key = key ?? $"/works/OL{_faker.Random.Number(1000, 9999)}W" + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponseFixture.cs new file mode 100644 index 00000000..2f440905 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingSummaryResponseFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryRatingSummaryResponseFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The average rating of the work. + /// Optional. The number of ratings of the work. + /// The created rating summary response. + public OpenLibraryRatingSummaryResponse Create(decimal? average = null, int? count = null) + { + return new OpenLibraryRatingSummaryResponse + { + Average = average ?? 4.5m, + Count = count ?? 100 + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs new file mode 100644 index 00000000..f55a8e5f --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryRatingsResponseFixture.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryRatingsResponseFixture +{ + private readonly OpenLibraryRatingSummaryResponseFixture _ratingSummaryResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The summary of the ratings of the work. + /// The created ratings response. + public OpenLibraryRatingsResponse Create(OpenLibraryRatingSummaryResponse? summary = null) + { + return new OpenLibraryRatingsResponse + { + Summary = summary ?? _ratingSummaryResponseFixture.Create() + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponseFixture.cs new file mode 100644 index 00000000..712e4d17 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibrarySearchDocumentResponseFixture.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibrarySearchDocumentResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the search document. + /// Optional. The title of the search document. + /// Optional. The author names of the search document. + /// Optional. The author keys of the search document. + /// Optional. The first publication year of the search document. + /// Optional. The edition keys of the search document. + /// Optional. The ISBNs of the search document. + /// Optional. The languages of the search document. + /// Optional. The publishers of the search document. + /// Optional. The subjects of the search document. + /// Optional. The publication places of the search document. + /// Optional. The median number of pages of the search document. + /// Optional. The average rating of the search document. + /// Optional. The number of ratings of the search document. + /// Optional. The Amazon identifiers of the search document. + /// Optional. The Goodreads identifiers of the search document. + /// Optional. The Google identifiers of the search document. + /// Optional. The LibraryThing identifiers of the search document. + /// Optional. The LCCN identifiers of the search document. + /// Optional. The OCLC identifiers of the search document. + /// The created search document response. + public OpenLibrarySearchDocumentResponse Create( + string? key = null, + string? title = null, + List? authorNames = null, + List? authorKeys = null, + int? firstPublishYear = null, + List? editionKeys = null, + List? isbns = null, + List? languages = null, + List? publishers = null, + List? subjects = null, + List? publishPlaces = null, + int? numberOfPagesMedian = null, + decimal? ratingsAverage = null, + int? ratingsCount = null, + List? amazonIds = null, + List? goodreadsIds = null, + List? googleIds = null, + List? libraryThingIds = null, + List? lccn = null, + List? oclc = null) + { + return new OpenLibrarySearchDocumentResponse + { + Key = key ?? $"/works/OL{_faker.Random.Number(1000, 9999)}W", + Title = title ?? _faker.Commerce.ProductName(), + AuthorNames = authorNames ?? [], + AuthorKeys = authorKeys ?? [], + FirstPublishYear = firstPublishYear, + EditionKeys = editionKeys ?? [], + Isbns = isbns ?? [], + Languages = languages ?? [], + Publishers = publishers ?? [], + Subjects = subjects ?? [], + PublishPlaces = publishPlaces ?? [], + NumberOfPagesMedian = numberOfPagesMedian, + RatingsAverage = ratingsAverage, + RatingsCount = ratingsCount, + AmazonIds = amazonIds ?? [], + GoodreadsIds = goodreadsIds ?? [], + GoogleIds = googleIds ?? [], + LibraryThingIds = libraryThingIds ?? [], + Lccn = lccn ?? [], + Oclc = oclc ?? [] + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs new file mode 100644 index 00000000..fb011624 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkAuthorResponseFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryWorkAuthorResponseFixture +{ + private readonly Faker _faker = new(); + private readonly OpenLibraryKeyReferenceResponseFixture _keyReferenceResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The author reference of the work. + /// Optional. The direct key of the author reference. + /// The created work author response. + public OpenLibraryWorkAuthorResponse Create( + OpenLibraryKeyReferenceResponse? author = null, + string? key = null) + { + return new OpenLibraryWorkAuthorResponse + { + Author = author ?? _keyReferenceResponseFixture.Create(key: $"/authors/OL{_faker.Random.Number(1000, 9999)}A"), + Key = key + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkResponseFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkResponseFixture.cs new file mode 100644 index 00000000..f7cf0e64 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/Contracts/Responses/OpenLibraryWorkResponseFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibraryWorkResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the work. + /// Optional. The title of the work. + /// Optional. The original title of the work. + /// Optional. The description of the work. + /// Optional. The first publication date of the work. + /// Optional. The subjects of the work. + /// Optional. The genres of the work. + /// Optional. The authors of the work. + /// Optional. The original languages of the work. + /// The created work response. + public OpenLibraryWorkResponse Create( + string? key = null, + string? title = null, + string? originalTitle = null, + JsonElement? description = null, + string? firstPublishDate = null, + List? subjects = null, + List? genres = null, + List? authors = null, + List? originalLanguages = null) + { + return new OpenLibraryWorkResponse + { + Key = key ?? $"/works/OL{_faker.Random.Number(1000, 9999)}W", + Title = title ?? _faker.Commerce.ProductName(), + OriginalTitle = originalTitle, + Description = description ?? default, + FirstPublishDate = firstPublishDate, + Subjects = subjects ?? [], + Genres = genres ?? [], + Authors = authors ?? [], + OriginalLanguages = originalLanguages ?? [] + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs new file mode 100644 index 00000000..9392328e --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Models/DTO/Settings/OpenLibrarySettingsDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal class OpenLibrarySettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The user agent sent with every request. + /// Optional. The contact email sent with every request. + /// Optional. The maximum number of search results. + /// Optional. The maximum number of editions fetched per work. + /// Optional. The minimum interval between consecutive requests. + /// The created . + public OpenLibrarySettingsDto Create( + string? userAgent = null, + string? contactEmail = null, + int? searchResultLimit = null, + int? workEditionLimit = null, + TimeSpan? minimumRequestInterval = null) + { + return new OpenLibrarySettingsDto + { + UserAgent = userAgent ?? _faker.Internet.UserAgent(), + ContactEmail = contactEmail, + SearchResultLimit = searchResultLimit ?? _faker.Random.Number(1, 50), + WorkEditionLimit = workEditionLimit ?? _faker.Random.Number(1, 200), + MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromMilliseconds(_faker.Random.Number(100, 2000)) + }; + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Setup/StubOpenLibraryHttpMessageHandler.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Setup/StubOpenLibraryHttpMessageHandler.cs new file mode 100644 index 00000000..d75a352b --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Common/Setup/StubOpenLibraryHttpMessageHandler.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.OpenLibrary.Fixtures.Common.Setup; + +/// +/// test double that routes requests to the configured responses based on their absolute path. +/// +[ExcludeFromCodeCoverage] +internal class StubOpenLibraryHttpMessageHandler : HttpMessageHandler +{ + private readonly List<(Func Matches, Func ResponseFactory)> _routes = []; + + /// + /// Gets the list of requests that were sent through this handler. + /// + public List Requests { get; } = []; + + /// + /// Routes requests with the given absolute path to the provided JSON response. + /// + /// The absolute path of the request URL to match. + /// The JSON payload of the response. + /// This handler, for chaining. + public StubOpenLibraryHttpMessageHandler MapPath(string absolutePath, string json) + { + return AddRoute( + request => string.Equals(request.RequestUri?.AbsolutePath, absolutePath, StringComparison.Ordinal), + _ => CreateJsonResponse(HttpStatusCode.OK, json)); + } + + /// + /// Routes requests matching the given predicate to the response produced by the provided factory. + /// + /// The predicate that determines whether the request matches the route. + /// The factory that produces the response for a matching request. + /// This handler, for chaining. + public StubOpenLibraryHttpMessageHandler AddRoute(Func matches, Func responseFactory) + { + _routes.Add((matches, responseFactory)); + return this; + } + + /// + /// Creates a JSON response with the given status code and payload. + /// + /// The status code of the response. + /// The JSON payload of the response. + /// The created JSON response. + public static HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, string json) + { + return new HttpResponseMessage(statusCode) + { + Content = new StringContent(json, Encoding.UTF8, "application/json") + }; + } + + /// + /// Sends the request to the first matching route, or returns a not found response. + /// + /// The HTTP request message to send. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Requests.Add(request); + foreach ((Func matches, Func responseFactory) in _routes) + if (matches(request)) + return Task.FromResult(responseFactory(request)); + + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); + } +} diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj new file mode 100644 index 00000000..96b62da1 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Lumina.Plugins.OpenLibrary.Fixtures.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.OpenLibrary.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..d244de92 --- /dev/null +++ b/tests/Common/Lumina.Plugins.OpenLibrary.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.OpenLibrary.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.OpenLibrary.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("A1B2C3D4-0002-4A5B-9C0D-222222222222")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.OpenLibrary.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj b/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj new file mode 100644 index 00000000..cb89b515 --- /dev/null +++ b/tests/Common/Lumina.TestPlugin/Lumina.TestPlugin.csproj @@ -0,0 +1,21 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + diff --git a/tests/Common/Lumina.TestPlugin/Properties/AssemblyInfo.cs b/tests/Common/Lumina.TestPlugin/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..84a4e9f1 --- /dev/null +++ b/tests/Common/Lumina.TestPlugin/Properties/AssemblyInfo.cs @@ -0,0 +1,16 @@ +using System.Reflection; +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.TestPlugin")] +[assembly: AssemblyProduct("Lumina.TestPlugin")] + +// 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("E5F6A7B8-0005-4C5D-9E0F-555555555555")] diff --git a/tests/Common/Lumina.TestPlugin/TestPlugin.cs b/tests/Common/Lumina.TestPlugin/TestPlugin.cs new file mode 100644 index 00000000..0d9c7ce7 --- /dev/null +++ b/tests/Common/Lumina.TestPlugin/TestPlugin.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.TestPlugin; + +/// +/// Test plugin used to verify the plugin loading pipeline of the host application. +/// +[ExcludeFromCodeCoverage] +public sealed class TestPlugin : IPlugin, IPluginServiceRegistrator +{ + public const string REGISTERED_MARKER = "plugin-services-registered"; + + /// + /// Gets the stable unique identifier of the plugin. + /// + public static Guid PluginId { get; } = Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"); + + /// + /// Gets the display name of the plugin. + /// + public static string PluginName { get; } = "Test Plugin"; + + /// + /// Gets the stable unique identifier of the plugin, used to persist its state. + /// + public Guid Id => PluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => PluginName; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Test Author"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "A test plugin used to verify the plugin loading pipeline."; + + /// + /// Gets the settings schema of the plugin, used by the host to render the plugin settings page. + /// + /// The collection of setting descriptors declared by the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services of the plugin into the host dependency injection container. + /// + /// The service collection to which the plugin services are added. + public void RegisterServices(IServiceCollection services) + { + services.AddSingleton(REGISTERED_MARKER); + } +} 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 bd119684..533da3dc 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/AuthenticatedLuminaApiFactory.cs @@ -164,9 +164,39 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable return user; } + /// + /// Removes the currently created test user from the database. + /// + /// + /// Test classes must call this in their per-test DisposeAsync instead of . The + /// factory is a shared , created once per test class and disposed by + /// xUnit only after all tests in the class have run. Calling from a per-test + /// DisposeAsync would dispose the web host and its service provider after the first test, making + /// every subsequent test in the class fail with an when it resolves + /// services. is therefore reserved for xUnit's own class-teardown and must never be + /// invoked from a test. + /// + /// A task representing the asynchronous operation. + public async Task RemoveTestUserAsync() + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername); + if (user is not null) + { + dbContext.Users.Remove(user); + await dbContext.SaveChangesAsync(); + } + } + /// /// Disposes API factory resources. /// + /// + /// Called by xUnit when the test class completes. Do not call from tests; per-test cleanup must use + /// . See that method for the details. + /// public new void Dispose() { using IServiceScope scope = Services.CreateScope(); @@ -178,5 +208,7 @@ public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable dbContext.Users.Remove(user); dbContext.SaveChanges(); } + + base.Dispose(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs index 73108052..d3291076 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Permissions/GetPermissionsEndpointTests.cs @@ -95,7 +95,7 @@ public class GetPermissionsEndpointTests : IClassFixture public async Task DisposeAsync() { - _apiFactory.Dispose(); + await _apiFactory.RemoveTestUserAsync(); using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs index d603fa35..2febffe9 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Admin/Authorization/Roles/AddRoleEndpointTests.cs @@ -115,7 +115,7 @@ public class AddRoleEndpointTests : IClassFixture Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); } [Fact] @@ -142,7 +142,7 @@ public class AddRoleEndpointTests : IClassFixture Assert.Equal("RoleAlreadyExists", problemDetails["detail"].GetString()); Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); } [Fact] @@ -182,6 +182,6 @@ public class AddRoleEndpointTests : IClassFixture await dbContext.SaveChangesAsync(); - _apiFactory.Dispose(); + await _apiFactory.RemoveTestUserAsync(); } } 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 ce531fd6..36436bda 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 @@ -103,7 +103,7 @@ public class DeleteRoleEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs index 7d274242..874ce09f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Drives/GetDrivesEndpointTests.cs @@ -42,10 +42,9 @@ public class GetDrivesEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs index 327ecd88..34a5af6f 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/FileSystem/GetTypeEndpointTests.cs @@ -99,9 +99,8 @@ public class GetTypeEndpointTests : IClassFixture /// /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs index 721f46cf..cca5008b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetFilesEndpointTests.cs @@ -256,9 +256,8 @@ public class GetFilesEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs index 2a670a3d..90f0f92a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Files/GetTreeFilesEndpointTests.cs @@ -256,9 +256,8 @@ public class GetTreeFilesEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs index b97fb2d0..6d20bd57 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CheckPathExistsEndpointTests.cs @@ -103,7 +103,7 @@ public class CheckPathExistsEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); Assert.Contains("General.Validation", errors.Keys); @@ -147,9 +147,8 @@ public class CheckPathExistsEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs index 79f1f22a..74066873 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/CombinePathEndpointTests.cs @@ -91,7 +91,7 @@ public class CombinePathEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -134,9 +134,8 @@ public class CombinePathEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs index 4864d8f0..6e5d328b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathParentEndpointTests.cs @@ -108,7 +108,7 @@ public class GetPathParentEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.Contains("General.Validation", errors.Keys); @@ -162,7 +162,7 @@ public class GetPathParentEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -205,9 +205,8 @@ public class GetPathParentEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs index a2089175..e434a376 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathRootEndpointTests.cs @@ -89,7 +89,7 @@ public class GetPathRootEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -119,7 +119,7 @@ public class GetPathRootEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -162,9 +162,8 @@ public class GetPathRootEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs index f6a58a3a..beb1af4e 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/GetPathSeparatorEndpointTests.cs @@ -113,9 +113,8 @@ public class GetPathSeparatorEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs index d76943d8..a54292a0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/SplitPathEndpointTests.cs @@ -92,7 +92,7 @@ public class SplitPathEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -121,7 +121,7 @@ public class SplitPathEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -149,9 +149,8 @@ public class SplitPathEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs index 88db300e..7485236c 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Path/ValidatePathEndpointTests.cs @@ -104,7 +104,7 @@ public class ValidatePathEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -132,9 +132,8 @@ public class ValidatePathEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs index 5ab48a06..dbe4b7d7 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/FileSystemManagement/Thumbnails/GetThumbnailEndpointTests.cs @@ -170,9 +170,8 @@ public class GetThumbnailEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs new file mode 100644 index 00000000..d19dd9a4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +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.Library.Management.AddLibrary; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedAdminClientAsync(); + } + + [Fact] + public async Task AddLibrary_WhenCalledWithValidData_ShouldCreateLibrary() + { + // Arrange + AddLibraryRequest request = new( + Title: "New Library", + LibraryType: "EBook", + ContentLocations: ["C:/Media"], + CoverImage: null, + IsEnabled: true, + IsLocked: false, + DownloadMetadataFromWeb: true, + ShouldSaveMetadataInMediaDirectories: false, + ShouldSkipUnchangedDirectoriesDuringScan: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + LibraryResponse? library = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(library); + Assert.Equal("New Library", library!.Title); + Assert.Equal(LibraryType.EBook, library.LibraryType); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == library.Id); + Assert.NotNull(storedLibrary); + Assert.Equal("New Library", storedLibrary!.Title); + } + + [Fact] + public async Task AddLibrary_WhenCalledByRegularUser_ShouldReturnForbidden() + { + // Arrange + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + AddLibraryRequest request = new( + Title: "New Library", + LibraryType: "EBook", + ContentLocations: ["C:/Media"], + CoverImage: null, + IsEnabled: true, + IsLocked: false, + DownloadMetadataFromWeb: true, + ShouldSaveMetadataInMediaDirectories: false, + ShouldSkipUnchangedDirectoriesDuringScan: true + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal("/api/v1/libraries", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + // clear junction tables first + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + + // then clear main tables + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Libraries.ExecuteDeleteAsync(); + + await dbContext.SaveChangesAsync(); + + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..0c0050af --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrariesScan; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CancelLibrariesScanEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task CancelLibrariesScan_WhenCalled_ShouldReturnNoContent() + { + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..d73add44 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibraryScan; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.Library.Management.CancelLibraryScan; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CancelLibraryScanEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task CancelLibraryScan_WhenScanDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryScanNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..d920832f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,195 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary; +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; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task DeleteLibrary_WhenLibraryExists_ShouldDeleteIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId); + Assert.Null(storedLibrary); + } + + [Fact] + public async Task DeleteLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task DeleteLibrary_WhenLibraryBelongsToAnotherUser_ShouldReturnForbidden() + { + // Arrange + Guid otherUserId = await SeedUserAsync(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, otherUserId); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Unauthorized", problemDetails["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// 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; + } + + /// + /// 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(); + } + + /// + /// 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/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..c0249927 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,138 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetEnabledLibraries; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetEnabledLibrariesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetEnabledLibraries_WhenEnabledLibrariesExist_ShouldReturnThem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid enabledLibraryId = Guid.NewGuid(); + await SeedLibraryAsync(enabledLibraryId, userId, "Enabled Library", isEnabled: true); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(libraries); + Assert.Contains(libraries!, library => library.Id == enabledLibraryId); + } + + [Fact] + public async Task GetEnabledLibraries_WhenOnlyDisabledLibrariesExist_ShouldReturnEmptyList() + { + // Arrange + Guid userId = GetCurrentUserId(); + await SeedLibraryAsync(Guid.NewGuid(), userId, "Disabled Library", isEnabled: false); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(libraries); + Assert.Empty(libraries!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// The title of the library. + /// Whether the library is enabled. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title, bool isEnabled) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = title, + LibraryType = LibraryType.EBook, + ContentLocations = [], + IsEnabled = isEnabled, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..f5fdf41f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,162 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraries; +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.Library.Management.GetLibraries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibrariesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraries_WhenLibrariesExist_ShouldReturnOnlyTheOwnedLibraries() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid otherUserId = await SeedUserAsync(); + Guid ownedLibraryId = Guid.NewGuid(); + Guid otherUserLibraryId = Guid.NewGuid(); + await SeedLibraryAsync(ownedLibraryId, userId, "Owned Library"); + await SeedLibraryAsync(otherUserLibraryId, otherUserId, "Other User Library"); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(libraries); + LibraryResponse ownedLibrary = Assert.Single(libraries!, library => library.Id == ownedLibraryId); + Assert.Equal("Owned Library", ownedLibrary.Title); + Assert.DoesNotContain(libraries, library => library.Id == otherUserLibraryId); + } + + [Fact] + public async Task GetLibraries_WhenNoLibrariesExist_ShouldReturnEmptyList() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse[]? libraries = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(libraries); + Assert.Empty(libraries!); + } + + /// + /// 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; + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// The title of the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = title, + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/Management/GetLibrary/GetLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs new file mode 100644 index 00000000..6acc6187 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.Library.Management.GetLibrary; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibrary_WhenLibraryExists_ShouldReturnIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, "Test Library"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse? library = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(library); + Assert.Equal(libraryId, library!.Id); + Assert.Equal("Test Library", library.Title); + } + + [Fact] + public async Task GetLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// The title of the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = title, + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs new file mode 100644 index 00000000..e30564f1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -0,0 +1,150 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetLibraryScanProgress; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryScanProgressEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryScanProgress_WhenLibraryDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task GetLibraryScanProgress_WhenScanIsNotTracked_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid scanId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryScanNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// 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(); + } + + /// + /// 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/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..39b86386 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetRunningLibraryScans; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetRunningLibraryScansEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetRunningLibraryScans_WhenNoScansAreRunning_ShouldReturnEmptyList() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/scans/running"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + IEnumerable? progress = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(progress); + Assert.Empty(progress!); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..39016988 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries; +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.Library.Management.ScanLibraries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ScanLibrariesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task ScanLibraries_WhenEnabledAndUnlockedLibrariesExist_ShouldStartScans() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { }); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + IEnumerable? scanResponses = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(scanResponses); + Assert.Contains(scanResponses!, scanResponse => scanResponse.LibraryId == libraryId); + } + + [Fact] + public async Task ScanLibraries_WhenNoLibrariesExist_ShouldReturnEmptyList() + { + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { }); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + IEnumerable? scanResponses = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(scanResponses); + Assert.Empty(scanResponses!); + } + + /// + /// Seeds an enabled and unlocked 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 = [], + IsEnabled = true, + IsLocked = false, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..965459d7 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.Library.Management.ScanLibrary; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ScanLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task ScanLibrary_WhenLibraryIsEnabledAndUnlocked_ShouldStartAScan() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, isEnabled: true, isLocked: false); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { }); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + MediaLibraryScanResponse? scanResponse = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(scanResponse); + Assert.Equal(libraryId, scanResponse!.LibraryId); + Assert.NotEqual(Guid.Empty, scanResponse.ScanId); + } + + [Fact] + public async Task ScanLibrary_WhenLibraryIsDisabled_ShouldReturnForbidden() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, isEnabled: false, isLocked: false); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { }); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString()); + Assert.Equal("General.Forbidden", problemDetails["title"].GetString()); + Assert.Equal("CannotScanDisabledLibrary", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + [Fact] + public async Task ScanLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { }); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/scans", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// Whether the library is enabled. + /// Whether the library is locked. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId, bool isEnabled, bool isLocked) + { + 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 = [], + IsEnabled = isEnabled, + IsLocked = isLocked, + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs new file mode 100644 index 00000000..8f7ab5ed --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -0,0 +1,178 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary; +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; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.Management.UpdateLibrary; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateLibraryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdateLibrary_WhenLibraryExists_ShouldUpdateIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId, "Original Title"); + UpdateLibraryRequest request = new( + Id: libraryId, + UserId: userId, + Title: "Updated Title", + LibraryType: "EBook", + ContentLocations: ["C:/Media"], + CoverImage: null, + IsEnabled: true, + IsLocked: false, + DownloadMetadataFromWeb: true, + ShouldSaveMetadataInMediaDirectories: false, + ShouldSkipUnchangedDirectoriesDuringScan: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + LibraryResponse? library = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(library); + Assert.Equal("Updated Title", library!.Title); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(lib => lib.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal("Updated Title", storedLibrary!.Title); + } + + [Fact] + public async Task UpdateLibrary_WhenLibraryDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + UpdateLibraryRequest request = new( + Id: libraryId, + UserId: Guid.NewGuid(), + Title: "Updated Title", + LibraryType: "EBook", + ContentLocations: ["C:/Media"], + CoverImage: null, + IsEnabled: true, + IsLocked: false, + DownloadMetadataFromWeb: true, + ShouldSaveMetadataInMediaDirectories: false, + ShouldSkipUnchangedDirectoriesDuringScan: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("LibraryNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// The title of the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId, string title) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = title, + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + 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/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs index 41dd66d5..05e297c6 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -1616,9 +1616,8 @@ public class AddBookEndpointTests : IClassFixture /// /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs new file mode 100644 index 00000000..36a07376 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetBook_WhenCalled_ShouldReturnOk() + { + // Arrange + Guid bookId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index ab76cfd6..9db061e1 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -352,9 +352,8 @@ public class GetBooksEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } 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 9071aed8..cc092581 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 @@ -402,9 +402,8 @@ public class GetBooksLiteEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } 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 3129a4ed..9a34d748 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 @@ -137,9 +137,8 @@ public class CheckInitializationEndpointTests : IClassFixture /// Disposes API factory resources. /// - public Task DisposeAsync() + public async Task DisposeAsync() { - _apiFactory.Dispose(); - return Task.CompletedTask; + await _apiFactory.RemoveTestUserAsync(); } } 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 fcef0165..73b9de47 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 @@ -152,7 +152,7 @@ public class SetupApplicationEndpointTests : IClassFixture +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckHealthEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckHealthEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task CheckHealth_WhenCalled_ShouldReturnOk() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/check-health"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} 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 new file mode 100644 index 00000000..4f54bb96 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; +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.GetLibraryMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryMetadataProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid userId = GetCurrentUserId(); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB, userId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-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 GetLibraryMetadataProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-providers"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? providers = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(providers); + Assert.Empty(providers!); + } + + /// + /// 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) + { + 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 + }); + 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/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..6823f24b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.GetPluginSettings; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPluginSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetPluginSettings_WhenPluginExists_ShouldReturnPluginSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + await SeedPluginAsync(pluginId, "Test Plugin"); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Lumina.Contracts.Responses.Plugins.PluginSettingsResponse? settings = await response.Content.ReadFromJsonAsync(_jsonOptions); + Assert.NotNull(settings); + Assert.Equal(pluginId, settings!.PluginId); + } + + [Fact] + public async Task GetPluginSettings_WhenPluginDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("PluginNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the plugin. + /// The display name of the plugin. + /// A task representing the asynchronous operation. + private async Task SeedPluginAsync(Guid pluginId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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 + }); + 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/GetPlugins/GetPluginsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs new file mode 100644 index 00000000..7975eba1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; +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.GetPlugins; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly List _seededPluginIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPluginsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetPlugins_WhenPluginsExist_ShouldReturnTheDetectedPlugins() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + await SeedPluginAsync(pluginId, "Test Plugin"); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? plugins = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(plugins); + Assert.Contains(plugins!, plugin => plugin.Id == pluginId && plugin.Name == "Test Plugin"); + } + + [Fact] + public async Task GetPlugins_WhenNoPluginsExist_ShouldReturnEmptyList() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? plugins = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(plugins); + Assert.Empty(plugins!); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the plugin. + /// The display name of the plugin. + /// A task representing the asynchronous operation. + private async Task SeedPluginAsync(Guid pluginId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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 + }); + 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. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + foreach (Guid pluginId in _seededPluginIds) + { + PluginEntity? plugin = await dbContext.Plugins.FindAsync(pluginId); + if (plugin is not null) + dbContext.Plugins.Remove(plugin); + } + await dbContext.SaveChangesAsync(); + await _apiFactory.RemoveTestUserAsync(); + } +} 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 new file mode 100644 index 00000000..c7f44e09 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,131 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; +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 + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryMetadataProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task ReorderLibraryMetadataProviders_WhenCalledWithValidData_ShouldReorderTheProviders() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid userId = GetCurrentUserId(); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, userId, rank: 1); + await SeedConfigurationAsync(libraryId, pluginIdB, userId, rank: 2); + ReorderLibraryMetadataProvidersRequest request = new( + LibraryId: libraryId, + PluginIds: [pluginIdB, pluginIdA] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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.LibraryMetadataProviderConfigurations + .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 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) + { + 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 + }); + 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/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..d55d16e4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +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 + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryMetadataProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task SetLibraryMetadataProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + SetLibraryMetadataProviderEnabledRequest request = new( + LibraryId: libraryId, + PluginId: pluginId, + IsEnabled: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + Assert.Equal(1, configuration.Rank); + } + + [Fact] + public async Task SetLibraryMetadataProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + Guid userId = GetCurrentUserId(); + await SeedConfigurationAsync(libraryId, pluginId, userId, isEnabled: false, rank: 1); + SetLibraryMetadataProviderEnabledRequest request = new( + LibraryId: libraryId, + PluginId: pluginId, + IsEnabled: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryMetadataProviderConfigurationEntity? configuration = await dbContext.LibraryMetadataProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + } + + /// + /// 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) + { + 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 + }); + 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/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs new file mode 100644 index 00000000..38398544 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; +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; +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.UpdatePluginSettings; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePluginSettingsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdatePluginSettings_WhenPluginExists_ShouldUpdateTheSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + await SeedPluginAsync(pluginId, "Test Plugin"); + UpdatePluginSettingsRequest request = new( + PluginId: pluginId, + Settings: new Dictionary { ["Key1"] = "Value1" } + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PluginEntity? storedPlugin = await dbContext.Plugins.FirstOrDefaultAsync(plugin => plugin.Id == pluginId); + Assert.NotNull(storedPlugin); + Assert.Contains("Value1", storedPlugin!.SettingsJson); + } + + [Fact] + public async Task UpdatePluginSettings_WhenPluginDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + UpdatePluginSettingsRequest request = new( + PluginId: pluginId, + Settings: new Dictionary { ["Key1"] = "Value1" } + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails["type"].GetString()); + Assert.Equal("General.NotFound", problemDetails["title"].GetString()); + Assert.Equal("PluginNotFound", problemDetails["detail"].GetString()); + Assert.Equal($"/api/v1/plugins/{pluginId}/settings", problemDetails["instance"].GetString()); + Assert.NotNull(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the plugin. + /// The display name of the plugin. + /// A task representing the asynchronous operation. + private async Task SeedPluginAsync(Guid pluginId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + 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 + }); + 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/UsersManagement/Authentication/ChangePasswordEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/ChangePasswordEndpointTests.cs index b7db86d7..35c5ba2f 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 @@ -104,7 +104,7 @@ public class ChangePasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -138,7 +138,7 @@ public class ChangePasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs index 81a6bb2e..5fc40108 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authentication/GetUsersEndpointTests.cs @@ -97,7 +97,7 @@ public class GetUsersEndpointTests : IClassFixture, Assert.Equal("TempPasswordExpired", problemDetails["detail"].GetString()); Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); } [Fact] @@ -203,7 +203,7 @@ public class LoginEndpointTests : IClassFixture, Assert.Equal("InvalidUsernameOrPassword", problemDetails["detail"].GetString()); Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); } [Fact] @@ -232,7 +232,7 @@ public class LoginEndpointTests : IClassFixture, Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); Assert.Equal("/api/v1/auth/login", problemDetails["instance"].GetString()); Assert.NotNull(problemDetails["traceId"].GetString()); - Assert.NotEmpty(problemDetails["traceId"].GetString()); + Assert.NotEmpty(problemDetails["traceId"].GetString()!); Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); 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 94803f37..1e9e1c9f 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 @@ -136,7 +136,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -193,7 +193,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -228,7 +228,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); @@ -280,7 +280,7 @@ public class RecoverPasswordEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); 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 93f69964..cea07a3b 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 @@ -117,7 +117,7 @@ public class GetAuthorizationEndpointTests : IClassFixture? errors = problemDetails["errors"].Deserialize>(_jsonOptions); Assert.NotNull(errors); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs index fa11ad9c..ffa66c79 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Authorization/GetUserPermissionsEndpointTests.cs @@ -121,7 +121,7 @@ public class GetUserPermissionsEndpointTests : IClassFixture, IDisposable { private readonly SqliteConnection _connection; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI="; /// @@ -95,6 +112,200 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable }); } + /// + /// Gets a unique IP address derived from a fresh GUID, to isolate the rate-limiting partition of each test. + /// + /// A unique IP address in the 192.168.0.0/16 private range. + public static string GetUniqueTestIp() + { + byte[] bytes = Guid.NewGuid().ToByteArray(); + return $"192.168.{bytes[0]}.{bytes[1]}"; + } + + /// + /// Creates a test user with the Admin role, authenticates it on , and returns its Id. + /// + /// The HTTP client to configure with authentication headers. + /// The Id of the created admin test user. + public async Task CreateAndAuthenticateAdminUserAsync(HttpClient client) + { + // a unique X-Forwarded-For isolates rate limiting state per test + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp()); + + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + 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 + }; + 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 + }; + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); + + return userId; + } + + /// + /// Creates a test user, authenticates it on , and returns its Id and username. + /// + /// The HTTP client to configure with authentication headers. + /// The Id and username of the created test user. + public async Task<(Guid UserId, string Username)> CreateAndAuthenticateUserAsync(HttpClient client) + { + // a unique X-Forwarded-For isolates rate limiting state per test + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", GetUniqueTestIp()); + + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + 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 + }; + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + string content = await loginResponse.Content.ReadAsStringAsync(); + LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); + + return (userId, username); + } + + /// + /// Removes a test user and its owned libraries from the database. + /// + /// The username of the test user to remove. + public async Task RemoveTestUserAsync(string username) + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity? user = await dbContext.Users.Include(candidate => candidate.Libraries).FirstOrDefaultAsync(candidate => candidate.Username == username).ConfigureAwait(false); + if (user is not null) + { + dbContext.Libraries.RemoveRange(user.Libraries); + dbContext.Users.Remove(user); + await dbContext.SaveChangesAsync(); + } + } + + /// + /// Removes a test admin user, its role, and its user-role link from the database. + /// + /// The Id of the admin test user to remove. + public async Task RemoveAdminUserAsync(Guid userId) + { + using IServiceScope scope = Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserRoleEntity? userRole = await dbContext.UserRoles.FirstOrDefaultAsync(candidate => candidate.UserId == userId).ConfigureAwait(false); + if (userRole is not null) + { + RoleEntity? role = await dbContext.Roles.FirstOrDefaultAsync(candidate => candidate.Id == userRole.RoleId).ConfigureAwait(false); + if (role is not null) + dbContext.Roles.Remove(role); + dbContext.UserRoles.Remove(userRole); + } + UserEntity? user = await dbContext.Users.FirstOrDefaultAsync(candidate => candidate.Id == userId).ConfigureAwait(false); + if (user is not null) + dbContext.Users.Remove(user); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + public async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + 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 + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a belonging to the media library identified by . + /// + /// The Id of the media library the book belongs to. + /// The title of the book. + public async Task SeedBookAsync(Guid libraryId, string title) + { + 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 + }); + await dbContext.SaveChangesAsync(); + } + /// /// Disposes the connection to the database. /// 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 fa738948..6b340d28 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,10 +1,19 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; @@ -13,13 +22,17 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati /// Contains security tests for the /auth/roles route. /// [ExcludeFromCodeCoverage] -public class AddRoleEndpointTests : IClassFixture +public class AddRoleEndpointTests : IClassFixture, IDisposable { private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private Guid _adminUserId; + private Guid _seededPermissionId; + private string _createdRoleName = ""; /// /// Initializes a new instance of the class. @@ -27,6 +40,7 @@ public class AddRoleEndpointTests : IClassFixture /// Injected in-memory API factory. public AddRoleEndpointTests(LuminaApiFactory apiFactory) { + _apiFactory = apiFactory; _client = apiFactory.CreateClient(); } @@ -57,4 +71,72 @@ public class AddRoleEndpointTests : IClassFixture Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddRole_WithSQLInjectionInRoleName_ShouldNotCorruptOrDeleteData(string maliciousRoleName) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + _seededPermissionId = Guid.NewGuid(); + 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 + }); + await seedDbContext.SaveChangesAsync(); + } + var requestBody = new + { + RoleName = maliciousRoleName, + Permissions = new[] { _seededPermissionId } + }; + _createdRoleName = maliciousRoleName; + StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await client.PostAsync("/api/v1/auth/roles", content); + + // Assert + // the malicious role name passes the authenticated handler and the permissions validation, reaches the + // parameterized insert, and is persisted verbatim: if it were concatenated into raw SQL, the insert would fail + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Roles.FirstOrDefaultAsync(role => role.RoleName == maliciousRoleName)); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + if (_seededPermissionId != Guid.Empty) + { + PermissionEntity? permission = dbContext.Permissions.FirstOrDefault(candidate => candidate.Id == _seededPermissionId); + if (permission is not null) + dbContext.Permissions.Remove(permission); + } + if (!string.IsNullOrEmpty(_createdRoleName)) + { + RoleEntity? createdRole = dbContext.Roles.FirstOrDefault(candidate => candidate.RoleName == _createdRoleName); + if (createdRole is not null) + dbContext.Roles.Remove(createdRole); + } + dbContext.SaveChanges(); + if (_adminUserId != Guid.Empty) + _apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult(); + } } 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 6192c9fd..f8ba0048 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,11 +1,20 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Contracts.Requests.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; @@ -14,13 +23,17 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Admin.Authorizati /// Contains security tests for the /auth/roles route. /// [ExcludeFromCodeCoverage] -public class UpdateRoleEndpointTests : IClassFixture +public class UpdateRoleEndpointTests : IClassFixture, IDisposable { private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true }; + private Guid _adminUserId; + private Guid _seededPermissionId; + private Guid _seededRoleId; /// /// Initializes a new instance of the class. @@ -28,6 +41,7 @@ public class UpdateRoleEndpointTests : IClassFixture /// Injected in-memory API factory. public UpdateRoleEndpointTests(LuminaApiFactory apiFactory) { + _apiFactory = apiFactory; _client = apiFactory.CreateClient(); } @@ -63,4 +77,82 @@ public class UpdateRoleEndpointTests : IClassFixture Assert.Equal("/api/v1/auth/roles", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } + + [Theory] + [InlineData("'; DROP TABLE Roles--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task UpdateRole_WithSQLInjectionInRoleName_ShouldNotCorruptOrDeleteData(string maliciousRoleName) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + _adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + _seededPermissionId = Guid.NewGuid(); + _seededRoleId = Guid.NewGuid(); + RoleEntity seededRole = new() + { + Id = _seededRoleId, + RoleName = "ExistingRole", + CreatedBy = Guid.NewGuid(), + CreatedOnUtc = DateTime.UtcNow + }; + 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.Roles.Add(seededRole); + await seedDbContext.SaveChangesAsync(); + } + UpdateRoleRequest requestBody = new( + RoleId: seededRole.Id, + RoleName: maliciousRoleName, + Permissions: [_seededPermissionId] + ); + StringContent content = new(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await client.PutAsync("/api/v1/auth/roles", content); + + // Assert + // the malicious role name passes the authenticated handler and the permissions validation, reaches the + // parameterized update, and is persisted verbatim: if it were concatenated into raw SQL, the update would fail + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + RoleEntity? updatedRole = await dbContext.Roles.FirstOrDefaultAsync(role => role.Id == seededRole.Id); + Assert.NotNull(updatedRole); + Assert.Equal(maliciousRoleName, updatedRole!.RoleName); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + if (_seededPermissionId != Guid.Empty) + { + PermissionEntity? permission = dbContext.Permissions.FirstOrDefault(candidate => candidate.Id == _seededPermissionId); + if (permission is not null) + dbContext.Permissions.Remove(permission); + } + if (_seededRoleId != Guid.Empty) + { + RoleEntity? role = dbContext.Roles.FirstOrDefault(candidate => candidate.Id == _seededRoleId); + if (role is not null) + dbContext.Roles.Remove(role); + } + dbContext.SaveChanges(); + if (_adminUserId != Guid.Empty) + _apiFactory.RemoveAdminUserAsync(_adminUserId).GetAwaiter().GetResult(); + } } 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 new file mode 100644 index 00000000..7e607c93 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.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; + +/// +/// Contains security tests for the /libraries route. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddLibraryEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + 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 + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries", 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", 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 AddLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle) + { + // 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 + ); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries", request); + + // Assert + // the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", 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); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Title == maliciousTitle); + Assert.NotNull(storedLibrary); + Assert.Equal(maliciousTitle, storedLibrary!.Title); + } +} 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 new file mode 100644 index 00000000..2a3e476b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries/scans/cancel route. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CancelLibrariesScanEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task CancelLibrariesScan_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { }); + + // 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/scans/cancel", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task CancelLibrariesScan_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans/cancel", new { }); + + // Assert + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..defa9e3b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; + +/// +/// Contains security tests for the /libraries/{libraryId}/scans/{scanId}/cancel route. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CancelLibraryScanEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task CancelLibraryScan_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string scanId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/cancel", new { }); + + // 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}/scans/{scanId}/cancel", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE LibraryScans--")] // destructive injection + public async Task CancelLibraryScan_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + // authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/cancel", new { }); + + // 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. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid userId) + { + 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 + }); + 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 new file mode 100644 index 00000000..f950d534 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; + +/// +/// Contains security tests for the /libraries/{id} route. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeleteLibraryEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task DeleteLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}"); + + // 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}", 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 DeleteLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}"); + + // Assert + // note: the {id} 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. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid userId) + { + 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 + }); + 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 new file mode 100644 index 00000000..e9e1557e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries/enabled route. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetEnabledLibrariesEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetEnabledLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/enabled"); + + // 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/enabled", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetEnabledLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/enabled"); + + // Assert + response.EnsureSuccessStatusCode(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..e642ca58 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries route. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibrariesEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries"); + + // 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", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync("/api/v1/libraries"); + + // Assert + response.EnsureSuccessStatusCode(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..8b3347ed --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -0,0 +1,176 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries/{id} route. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}"); + + // 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}", 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 GetLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}"); + + // Assert + // note: the {id} 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 + // note: the payloads never contain the literal "SQL", so checking for that word would assert nothing; what matters + // is that the injection never reaches the database, so no SQL engine error (SqliteException) may surface + 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); + } + + [Fact] + public async Task GetLibrary_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}"); + + // Assert + 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); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid userId) + { + 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 + }); + await dbContext.SaveChangesAsync(); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..6cb3193f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; + +/// +/// Contains security tests for the /libraries/{libraryId}/scans/{scanId}/progress route. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryScanProgressEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibraryScanProgress_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string scanId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/scans/{scanId}/progress"); + + // 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}/scans/{scanId}/progress", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE LibraryScans--")] // destructive injection + public async Task GetLibraryScanProgress_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + // authenticate with an admin user and seed a library, so a valid libraryId would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/scans/{Guid.NewGuid()}/progress"); + + // 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. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid userId) + { + 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 + }); + 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 new file mode 100644 index 00000000..2f24ed6b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries/scans/running route. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetRunningLibraryScansEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetRunningLibraryScans_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/libraries/scans/running"); + + // 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/scans/running", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetRunningLibraryScans_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.GetAsync("/api/v1/libraries/scans/running"); + + // Assert + response.EnsureSuccessStatusCode(); + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..771ab9f2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.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; + +/// +/// Contains security tests for the /libraries/scans route. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly PasswordHashService _hashService = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ScanLibrariesEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ScanLibraries_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/libraries/scans", new { }); + + // 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/scans", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task ScanLibraries_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + await CreateAndAuthenticateUserAsync(client); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/libraries/scans", new { }); + + // Assert + 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); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// A task representing the asynchronous operation. + private async Task CreateAndAuthenticateUserAsync(HttpClient client) + { + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + 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 + }); + await dbContext.SaveChangesAsync(); + + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "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 new file mode 100644 index 00000000..0fd9755f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; + +/// +/// Contains security tests for the /libraries/{id}/scans route. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ScanLibraryEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ScanLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"/api/v1/libraries/{libraryId}/scans", new { }); + + // 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}/scans", 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 ScanLibrary_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library, so a valid id would reach the handler and be authorized + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedLibraryAsync(userId); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/scans", new { }); + + // Assert + // note: the {id} 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. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid userId) + { + 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 + }); + 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 new file mode 100644 index 00000000..71272286 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Contracts.Requests.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.UpdateLibrary; + +/// +/// Contains security tests for the /libraries/{id} route. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdateLibraryEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task UpdateLibrary_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // 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 + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", 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}", 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 UpdateLibrary_WithSQLInjectionInTitle_ShouldNotLeakOrError(string maliciousTitle) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + 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 + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}", request); + + // Assert + // the malicious title passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", 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); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryEntity? storedLibrary = await dbContext.Libraries.FirstOrDefaultAsync(library => library.Id == libraryId); + Assert.NotNull(storedLibrary); + Assert.Equal(maliciousTitle, storedLibrary!.Title); + } + + /// + /// 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(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs new file mode 100644 index 00000000..436a84ff --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +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.WrittenContentLibrary.BookLibrary.Books.AddBook; + +/// +/// Contains security tests for the /books route. +/// +[ExcludeFromCodeCoverage] +public class AddBookEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaApiFactory _apiFactory; + private readonly AddBookRequestFixture _addBookRequestFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddBookEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task AddBook_WithSQLInjectionInPath_ShouldNotCorruptOrDeleteData(string maliciousPath) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, userId); + AddBookRequest request = _addBookRequestFixture.Create() with { LibraryId = libraryId, Path = maliciousPath }; + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/books", request); + + // Assert + // the malicious path passes the authenticated handler, reaches the parameterized insert, and is persisted + // verbatim: if it were concatenated into raw SQL, the insert would fail and the book would not be created + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Libraries.CountAsync(library => library.Id == libraryId)); + // the single book in the library is the one inserted by this request, with the malicious path stored as data + Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId)); + + await _apiFactory.RemoveTestUserAsync(username); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + // nothing to clean up: each test removes its own seeded rows + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs new file mode 100644 index 00000000..3e64f24e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; + +/// +/// Contains security tests for the /books/{id} route. +/// +[ExcludeFromCodeCoverage] +public class GetBookEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetBookEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetBook_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Arrange + Guid bookId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{bookId}"); + + // Assert + 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); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Books--")] // destructive injection + public async Task GetBook_WithSQLInjectionInBookId_ShouldNotLeakOrError(string maliciousBookId) + { + // Arrange + // the {id} route parameter is string-typed, so the malicious value binds and reaches the anonymous endpoint handler + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/books/{Uri.EscapeDataString(maliciousBookId)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // the endpoint processes the value without querying the persistence medium and without leaking it + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", 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.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs index 801cc034..98f13088 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooks/GetBooksEndpointTests.cs @@ -1,20 +1,14 @@ #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.Contracts.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.Diagnostics.CodeAnalysis; using System.Net; -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.WrittenContentLibrary.BookLibrary.Books.GetBooks; @@ -23,11 +17,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo /// Contains security tests for the /books route. /// [ExcludeFromCodeCoverage] -public class GetBooksEndpointTests : IClassFixture +public class GetBooksEndpointTests : IClassFixture, IDisposable { private readonly HttpClient _client; private readonly LuminaApiFactory _apiFactory; - private readonly PasswordHashService _hashService = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -64,16 +57,16 @@ public class GetBooksEndpointTests : IClassFixture } [Theory] - [InlineData("' OR '1'='1")] // basic SQL injection - [InlineData("'; DROP TABLE Books--")] // destructive injection - public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotLeakOrError(string maliciousSearchTerm) + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooks_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) { // Arrange HttpClient client = _apiFactory.CreateClient(); - Guid userId = await CreateAndAuthenticateUserAsync(client); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); Guid libraryId = Guid.NewGuid(); - await SeedLibraryAsync(libraryId, userId); - await SeedBookAsync(libraryId, "Book A"); + await _apiFactory.SeedLibraryAsync(libraryId, userId); + await _apiFactory.SeedBookAsync(libraryId, "Book A"); // Act HttpResponseMessage response = await client.GetAsync($"/api/v1/books?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); @@ -81,89 +74,21 @@ public class GetBooksEndpointTests : IClassFixture // Assert response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); - Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + + // the injected statement must never be executed: the Books table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId)); + + await _apiFactory.RemoveTestUserAsync(username); } /// - /// Creates a test user, authenticates it on , and returns its Id. + /// Disposes API factory resources. /// - /// The HTTP client to authenticate. - /// The Id of the created test user. - private async Task CreateAndAuthenticateUserAsync(HttpClient client) + public void Dispose() { - client.DefaultRequestHeaders.Clear(); - client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.{Random.Shared.Next(1, 255)}"); - - using IServiceScope scope = _apiFactory.Services.CreateScope(); - 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 - }); - await dbContext.SaveChangesAsync(); - - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); - string content = await loginResponse.Content.ReadAsStringAsync(); - LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); - - return userId; - } - - /// - /// 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 belonging to the media library identified by . - /// - /// The Id of the media library the book belongs to. - /// The title of the book. - /// A task representing the asynchronous operation. - private async Task SeedBookAsync(Guid libraryId, string title) - { - using IServiceScope scope = _apiFactory.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 - }); - await dbContext.SaveChangesAsync(); + // nothing to clean up: each test removes its own seeded rows } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs index c9a61386..fb62b38f 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBooksLite/GetBooksLiteEndpointTests.cs @@ -1,9 +1,15 @@ #region ========================================================================= USING ===================================================================================== +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.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.WrittenContentLibrary.BookLibrary.Books.GetBooksLite; @@ -12,9 +18,10 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenCo /// Contains security tests for the /books/lite route. /// [ExcludeFromCodeCoverage] -public class GetBooksLiteEndpointTests : IClassFixture +public class GetBooksLiteEndpointTests : IClassFixture, IDisposable { private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -26,6 +33,7 @@ public class GetBooksLiteEndpointTests : IClassFixture /// Injected in-memory API factory. public GetBooksLiteEndpointTests(LuminaApiFactory apiFactory) { + _apiFactory = apiFactory; _client = apiFactory.CreateClient(); } @@ -48,4 +56,40 @@ public class GetBooksLiteEndpointTests : IClassFixture Assert.Equal("/api/v1/books/lite", problemDetails["instance"].GetProperty("value").GetString()); Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); } + + [Theory] + [InlineData("'; DROP TABLE Books; --")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task GetBooksLite_WhenSearchTermContainsSqlInjection_ShouldNotCorruptOrDeleteData(string maliciousSearchTerm) + { + // Arrange + HttpClient client = _apiFactory.CreateClient(); + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + Guid libraryId = Guid.NewGuid(); + await _apiFactory.SeedLibraryAsync(libraryId, userId); + await _apiFactory.SeedBookAsync(libraryId, "Book A"); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/books/lite?libraryId={libraryId}&searchTerm={Uri.EscapeDataString(maliciousSearchTerm)}"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + + // the injected statement must never be executed: the Books table and the seeded rows must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await dbContext.Books.CountAsync(book => book.LibraryId == libraryId)); + + await _apiFactory.RemoveTestUserAsync(username); + } + + /// + /// Disposes API factory resources. + /// + public void Dispose() + { + // nothing to clean up: each test removes its own seeded rows + } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs new file mode 100644 index 00000000..adce30ab --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Maintenance; + +/// +/// Contains security tests for the /check-health route. +/// +[ExcludeFromCodeCoverage] +public class CheckHealthEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CheckHealthEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task CheckHealth_WhenCalledWithoutAuthentication_ShouldBeAccessible() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/check-health"); + + // Assert + 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/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..d215cd92 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.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; + +/// +/// Contains security tests for the /libraries/{libraryId}/metadata-providers route. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/metadata-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}/metadata-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 GetLibraryMetadataProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library with a metadata 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, userId); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/metadata-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(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a 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) + { + 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 + }); + 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 new file mode 100644 index 00000000..0dce62e1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,118 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; + +/// +/// Contains security tests for the /plugins/{pluginId}/settings route. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPluginSettingsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetPluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string pluginId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/plugins/{pluginId}/settings"); + + // 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/plugins/{pluginId}/settings", 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 GetPluginSettings_WithSQLInjectionInPluginId_ShouldNotLeakOrError(string maliciousPluginId) + { + // 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); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings"); + + // Assert + // note: the {pluginId} 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 created by . + /// + /// The Id of the creator. + /// A task representing the asynchronous operation. + private async Task SeedPluginAsync(Guid userId) + { + 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 + }); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs new file mode 100644 index 00000000..7464eb31 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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.GetPlugins; + +/// +/// Contains security tests for the /plugins route. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPluginsEndpointTests(LuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetPlugins_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/plugins"); + + // 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/plugins", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } +} 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 new file mode 100644 index 00000000..26964523 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.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; + +/// +/// Contains security tests for the /libraries/{libraryId}/metadata-providers/reorder route. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryMetadataProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ReorderLibraryMetadataProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + ReorderLibraryMetadataProvidersRequest request = new( + LibraryId: Guid.NewGuid(), + PluginIds: [Guid.NewGuid()] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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}/metadata-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 ReorderLibraryMetadataProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) + { + // Arrange + // authenticate with an admin user and seed a library with metadata 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, userId, rank: 1); + await SeedConfigurationAsync(libraryId, userId, 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}/metadata-providers/reorder", + new { libraryId = 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(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a 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) + { + 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 + }); + 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 new file mode 100644 index 00000000..d25358e1 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.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; + +/// +/// Contains security tests for the /libraries/{libraryId}/metadata-providers/{pluginId}/enabled route. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryMetadataProviderEnabledEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task SetLibraryMetadataProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string pluginId = Guid.NewGuid().ToString(); + SetLibraryMetadataProviderEnabledRequest request = new( + LibraryId: Guid.NewGuid(), + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/metadata-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}/metadata-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 SetLibraryMetadataProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + // authenticate with an admin user and seed a library with a metadata 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, userId); + SetLibraryMetadataProviderEnabledRequest request = new( + LibraryId: libraryId, + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/metadata-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(new LibraryEntity + { + Id = libraryId, + UserId = userId, + Title = "Test Library", + LibraryType = LibraryType.EBook, + ContentLocations = [], + CreatedBy = userId, + CreatedOnUtc = DateTime.UtcNow, + UpdatedBy = null + }); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a 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) + { + 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 + }); + 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 new file mode 100644 index 00000000..0a63870d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Requests.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.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; + +/// +/// Contains security tests for the /plugins/{pluginId}/settings route. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePluginSettingsEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task UpdatePluginSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string pluginId = Guid.NewGuid().ToString(); + UpdatePluginSettingsRequest request = new( + PluginId: Guid.NewGuid(), + Settings: new Dictionary { ["Key"] = "Value" } + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", 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/plugins/{pluginId}/settings", 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 UpdatePluginSettings_WithSQLInjectionInSettings_ShouldNotLeakOrError(string maliciousValue) + { + // 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 } + ); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/plugins/{pluginId}/settings", request); + + // Assert + // the malicious value passes the authenticated handler, reaches the parameterized data access, and is persisted verbatim + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", 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); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PluginEntity? storedPlugin = await dbContext.Plugins.FirstOrDefaultAsync(plugin => plugin.Id == pluginId); + Assert.NotNull(storedPlugin); + Assert.NotNull(storedPlugin!.SettingsJson); + Dictionary? storedSettings = JsonSerializer.Deserialize>(storedPlugin.SettingsJson!); + Assert.NotNull(storedSettings); + Assert.Equal(maliciousValue, storedSettings!["Key"]); + } + + /// + /// Seeds a created by . + /// + /// The Id of the creator. + /// The Id of the seeded plugin. + private async Task SeedPluginAsync(Guid userId) + { + 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 + }); + await dbContext.SaveChangesAsync(); + return pluginId; + } +} 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 bca24809..7b5ef556 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 @@ -6,8 +6,8 @@ using Lumina.DataAccess.Core.UoW; 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http.Headers; @@ -74,41 +74,68 @@ public class ChangePasswordEndpointTests : IClassFixture, IDis } [Fact] - public async Task ChangePassword_WithValidRequest_ShouldNotLeakTimingInformation() + public async Task ChangePassword_WithWrongCurrentPassword_ShouldReturnUniformForbiddenResponse() { // Arrange UserEntity user = await CreateAndAuthenticateUser(); - Stopwatch stopwatch = new(); - List timings = []; + ChangePasswordRequest request = new( + Username: user.Username, + CurrentPassword: "WrongPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); // Act - for (int i = 0; i < 10; i++) - { - await Task.Delay(100); - stopwatch.Restart(); - await _client.PostAsJsonAsync("/api/v1/auth/change-password", new ChangePasswordRequest( - Username: user.Username, - CurrentPassword: "WrongPass123!", - NewPassword: "NewPass123!", - NewPasswordConfirm: "NewPass123!" - )); - stopwatch.Stop(); - timings.Add(stopwatch.ElapsedMilliseconds); - } - - timings.Sort(); - timings = timings.Skip(1).SkipLast(1).ToList(); // remove outliers + HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + string firstContent = await firstResponse.Content.ReadAsStringAsync(); + HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + string secondContent = await secondResponse.Content.ReadAsStringAsync(); // Assert - double stdDev = CalculateStandardDeviation(timings); - Assert.True(stdDev < 200); + Assert.Equal(HttpStatusCode.Forbidden, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, secondResponse.StatusCode); + AssertProblemDetail(firstContent, "General.Failure", "InvalidCurrentPassword"); + AssertProblemDetail(secondContent, "General.Failure", "InvalidCurrentPassword"); } - private static double CalculateStandardDeviation(List values) + [Theory] + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task ChangePassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername) { - double average = values.Average(); - double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); - return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + // Arrange + UserEntity user = await CreateAndAuthenticateUser(); + string originalPasswordHash = user.Password; + ChangePasswordRequest request = new( + Username: maliciousUsername, + CurrentPassword: "TestPass123!", + NewPassword: "NewPass123!", + NewPasswordConfirm: "NewPass123!" + ); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync("/api/v1/auth/change-password", request); + + // Assert + // the malicious username is queried by GetByUsernameAsync, so it must never be executed against the database; + // if a boolean-injection regression returned the only user in the database, the current password would match and + // the password would change, so the response must be a failure and the stored password hash must be unchanged + Assert.NotEqual(HttpStatusCode.OK, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity? storedUser = await dbContext.Users.FirstOrDefaultAsync(candidate => candidate.Id == user.Id); + Assert.NotNull(storedUser); + Assert.Equal(originalPasswordHash, storedUser!.Password); + } + + private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(expectedTitle, problemDetails!["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } private async Task CreateAndAuthenticateUser() 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 810079cb..30b2a097 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 @@ -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; @@ -8,8 +9,8 @@ using Lumina.Infrastructure.Core.Authentication; 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IdentityModel.Tokens.Jwt; using System.Net; @@ -27,6 +28,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A public class LoginEndpointTests : IClassFixture, IDisposable { private readonly PasswordHashService _hashService = new(); + private readonly UserEntityFixture _userEntityFixture = new(); private readonly ICryptographyService _cryptographyService; private readonly TotpTokenGenerator _totpTokenGenerator = new(); private readonly LuminaApiFactory _apiFactory; @@ -110,36 +112,32 @@ public class LoginEndpointTests : IClassFixture, IDisposable } [Fact] - public async Task Login_WithValidCredentials_ShouldNotLeakTimingInformation() + public async Task Login_WithUnknownUsernameAndWrongPassword_ShouldReturnIndistinguishableResponses() { // Arrange UserEntity user = await CreateTestUser(); - Stopwatch stopwatch = new(); - List timings = []; - // since this test is rigged to trigger the rate limiting, assign a different IP to it + LoginRequest unknownUserRequest = new( + Username: "nonexistent_user", + Password: "TestPass123!" + ); + LoginRequest wrongPasswordRequest = new( + Username: user.Username, + Password: "WrongPass123!" + ); _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.2"); // Act - for (int i = 0; i < 10; i++) - { - await Task.Delay(100); // add small delay between requests - stopwatch.Restart(); - await _client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest( - Username: user.Username, - Password: "TestPass123!" - )); - stopwatch.Stop(); - timings.Add(stopwatch.ElapsedMilliseconds); - } - // remove the highest and lowest values to account for outliers - timings.Sort(); - timings = timings.Skip(1).SkipLast(1).ToList(); + HttpResponseMessage unknownUserResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", unknownUserRequest); + string unknownUserContent = await unknownUserResponse.Content.ReadAsStringAsync(); + HttpResponseMessage wrongPasswordResponse = await _client.PostAsJsonAsync("/api/v1/auth/login", wrongPasswordRequest); + string wrongPasswordContent = await wrongPasswordResponse.Content.ReadAsStringAsync(); // Assert - // check for timing consistency to prevent timing attacks - double stdDev = CalculateStandardDeviation(timings); - Assert.True(stdDev < 200); + Assert.Equal(HttpStatusCode.Forbidden, unknownUserResponse.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, wrongPasswordResponse.StatusCode); + AssertProblemDetail(unknownUserContent, "General.Failure", "InvalidUsernameOrPassword"); + AssertProblemDetail(wrongPasswordContent, "General.Failure", "InvalidUsernameOrPassword"); } [Fact] @@ -202,6 +200,11 @@ public class LoginEndpointTests : IClassFixture, IDisposable Assert.DoesNotContain("Exception", content); Assert.DoesNotContain(legitimateUser.Username, content); // shouldn't expose other usernames Assert.DoesNotContain(legitimateUser.Password, content); // shouldn't expose password hashes + + // the injected statement must never be executed: the Users table and the seeded user must still be there + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id)); } [Fact] @@ -247,11 +250,12 @@ public class LoginEndpointTests : IClassFixture, IDisposable Assert.DoesNotContain("Exception", content); } - private double CalculateStandardDeviation(List values) + private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) { - double average = values.Average(); - double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); - return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(expectedTitle, problemDetails!["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } private async Task CreateTestUser() @@ -259,16 +263,8 @@ public class LoginEndpointTests : IClassFixture, IDisposable using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - 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/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs index 2e0b2dfe..b2425704 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Authentication/RecoverPasswordEndpointTests.cs @@ -1,15 +1,23 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Requests.Authentication; using Lumina.DataAccess.Core.UoW; +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.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.SecurityTests.Core.Endpoints.UsersManagement.Authentication; @@ -22,6 +30,8 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi { private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; + private readonly PasswordHashService _hashService = new(); + private readonly UserEntityFixture _userEntityFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -75,6 +85,52 @@ public class RecoverPasswordEndpointTests : IClassFixture, IDi Assert.True(lastResponse.Headers.Contains("X-RateLimit-Remaining")); } + [Theory] + [InlineData("'; DROP TABLE Users--")] // destructive injection + [InlineData("' OR '1'='1")] // boolean-based injection + public async Task RecoverPassword_WithSQLInjectionInUsername_ShouldNotCorruptOrDeleteData(string maliciousUsername) + { + // Arrange + // use a dedicated unique IP, so the rate-limit test (which exhausts the 10-permit window on its own IP) + // cannot run first and 429 this test; the NotEqual(TooManyRequests) assertion below guards against any collision + HttpClient client = _apiFactory.CreateClient(); + client.DefaultRequestHeaders.Clear(); + client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp()); + UserEntity legitimateUser = await CreateTestUser(); + RecoverPasswordRequest request = new( + Username: maliciousUsername, + TotpCode: "123456" + ); + + // Act + HttpResponseMessage response = await client.PostAsJsonAsync("/api/v1/auth/recover-password", request); + + // Assert + // the malicious username queries for a user, so it must never be executed against the database + Assert.NotEqual(HttpStatusCode.TooManyRequests, response.StatusCode); + Assert.DoesNotContain("SqliteException", await response.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.NotNull(await dbContext.Users.FirstOrDefaultAsync(user => user.Id == legitimateUser.Id)); + } + + /// + /// Creates a test user in the database. + /// + /// The created user entity. + private async Task CreateTestUser() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity user = _userEntityFixture.Create(username: _testUsername, password: _hashService.HashString("TestPass123!")); + + dbContext.Users.Add(user); + await dbContext.SaveChangesAsync(); + return user; + } + public void Dispose() { using IServiceScope scope = _apiFactory.Services.CreateScope(); 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 7222650d..9253aa36 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,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Requests.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http.Json; @@ -23,6 +23,7 @@ namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.A public class RegisterEndpointTests : IClassFixture, IDisposable { private readonly PasswordHashService _hashService = new(); + private readonly UserEntityFixture _userEntityFixture = new(); private readonly LuminaApiFactory _apiFactory; private readonly HttpClient _client; private readonly JsonSerializerOptions _jsonOptions = new() @@ -42,34 +43,29 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl } [Fact] - public async Task Register_WithValidData_ShouldNotLeakTimingInformation() + public async Task Register_WhenUsernameTaken_ShouldReturnUniformConflictResponse() { // Arrange - Stopwatch stopwatch = new(); - List timings = []; - _client.DefaultRequestHeaders.Clear(); - _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6"); RegistrationRequest request = new( Username: _testUsername, Password: "TestPass123!", PasswordConfirm: "TestPass123!" ); + _client.DefaultRequestHeaders.Clear(); + _client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.168.1.6"); // Act - for (int i = 0; i < 10; i++) - { - await Task.Delay(100); - stopwatch.Restart(); - await _client.PostAsJsonAsync("/api/v1/auth/register", request); - stopwatch.Stop(); - timings.Add(stopwatch.ElapsedMilliseconds); - } - timings.Sort(); - timings = timings.Skip(1).SkipLast(1).ToList(); + HttpResponseMessage firstResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + HttpResponseMessage secondResponse = await _client.PostAsJsonAsync("/api/v1/auth/register", request); + string secondContent = await secondResponse.Content.ReadAsStringAsync(); // Assert - double stdDev = CalculateStandardDeviation(timings); - Assert.True(stdDev < 200); + Assert.Equal(HttpStatusCode.Created, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.Conflict, secondResponse.StatusCode); + AssertProblemDetail(secondContent, "General.Conflict", "UsernameAlreadyExists"); + Assert.DoesNotContain("password", secondContent); + Assert.DoesNotContain("hash", secondContent); + Assert.DoesNotContain("salt", secondContent); } [Fact] @@ -116,6 +112,8 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl public async Task Register_WithSQLInjectionAttempt_ShouldRemainSecure(string maliciousUsername) { // 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!", @@ -203,11 +201,12 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl Assert.DoesNotContain("salt", content); } - private double CalculateStandardDeviation(List values) + private void AssertProblemDetail(string content, string expectedTitle, string expectedDetail) { - double average = values.Average(); - double sumOfSquaresOfDifferences = values.Select(value => (value - average) * (value - average)).Sum(); - return Math.Sqrt(sumOfSquaresOfDifferences / values.Count); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(expectedTitle, problemDetails!["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); } private async Task CreateTestUser() @@ -215,16 +214,7 @@ public class RegisterEndpointTests : IClassFixture, IDisposabl using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - UserEntity user = new() - { - 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!")); dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); 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 0e12b100..f1ace1b9 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,5 +41,7 @@ + + diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs index 2f2b3fe8..644fc74e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/GenreMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -16,13 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class GenreMappingTests { + private readonly GenreFixture _genreFixture = new(); + [Fact] public void ToRepositoryEntity_WhenMappingGenre_ShouldMapCorrectly() { // Arrange - Result createResult = Genre.Create("Rock"); - Assert.False(createResult.IsFailure); - Genre genre = createResult.Value; + Genre genre = _genreFixture.Create("Rock"); // Act GenreEntity result = genre.ToRepositoryEntity(); @@ -40,9 +40,7 @@ public class GenreMappingTests public void ToRepositoryEntity_WhenMappingDifferentGenres_ShouldMapCorrectly(string name) { // Arrange - Result createResult = Genre.Create(name); - Assert.False(createResult.IsFailure); - Genre genre = createResult.Value; + Genre genre = _genreFixture.Create(name); // Act GenreEntity result = genre.ToRepositoryEntity(); @@ -58,10 +56,10 @@ public class GenreMappingTests // Arrange List genres = [ - Genre.Create("Rock").Value, - Genre.Create("Jazz").Value, - Genre.Create("Classical").Value, - Genre.Create("Pop").Value + _genreFixture.Create("Rock"), + _genreFixture.Create("Jazz"), + _genreFixture.Create("Classical"), + _genreFixture.Create("Pop") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs index 4e327b3f..738cc90b 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Common/Metadata/TagMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.Mapping.Common.Metadata; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -16,13 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.Common.Metadata; [ExcludeFromCodeCoverage] public class TagMappingTests { + private readonly TagFixture _tagFixture = new(); + [Fact] public void ToRepositoryEntity_WhenMappingTag_ShouldMapCorrectly() { // Arrange - Result createResult = Tag.Create("indie"); - Assert.False(createResult.IsFailure); - Tag tag = createResult.Value; + Tag tag = _tagFixture.Create("indie"); // Act TagEntity result = tag.ToRepositoryEntity(); @@ -41,9 +41,7 @@ public class TagMappingTests public void ToRepositoryEntity_WhenMappingDifferentTags_ShouldMapCorrectly(string name) { // Arrange - Result createResult = Tag.Create(name); - Assert.False(createResult.IsFailure); - Tag tag = createResult.Value; + Tag tag = _tagFixture.Create(name); // Act TagEntity result = tag.ToRepositoryEntity(); @@ -59,11 +57,11 @@ public class TagMappingTests // Arrange List tags = [ - Tag.Create("indie").Value, - Tag.Create("electronic").Value, - Tag.Create("instrumental").Value, - Tag.Create("live").Value, - Tag.Create("acoustic").Value + _tagFixture.Create("indie"), + _tagFixture.Create("electronic"), + _tagFixture.Create("instrumental"), + _tagFixture.Create("live"), + _tagFixture.Create("acoustic") ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs index 4baff100..79308cea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/UnixRootItemMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,13 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileS [ExcludeFromCodeCoverage] public class UnixRootItemMappingTests { + private readonly UnixRootItemFixture _unixRootItemFixture = new(); + [Fact] public void ToTreeNodeResponse_WhenMappingUnixRootItem_ShouldMapCorrectly() { // Arrange - Result createResult = UnixRootItem.Create(); - Assert.False(createResult.IsFailure); - UnixRootItem domainModel = createResult.Value; + UnixRootItem domainModel = _unixRootItemFixture.Create(); // Act FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs index 50beb89a..d671f0da 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/FileSystem/WindowsRootItemMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem; using Lumina.Contracts.Responses.FileSystemManagement.Common; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Diagnostics.CodeAnalysis; #endregion @@ -15,15 +15,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.FileS [ExcludeFromCodeCoverage] public class WindowsRootItemMappingTests { + private readonly WindowsRootItemFixture _windowsRootItemFixture = new(); + [Fact] public void ToTreeNodeResponse_WhenMappingWindowsRootItem_ShouldMapCorrectly() { // Arrange - string path = "C:\\"; - string name = "C:"; - Result createResult = WindowsRootItem.Create(path, name); - Assert.False(createResult.IsFailure); - WindowsRootItem domainModel = createResult.Value; + WindowsRootItem domainModel = _windowsRootItemFixture.Create(path: "C:\\", name: "C:"); // Act FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); @@ -42,12 +40,7 @@ public class WindowsRootItemMappingTests public void ToTreeNodeResponse_WhenMappingWindowsRootItemWithCustomStatus_ShouldMapCorrectly() { // Arrange - string path = "D:\\"; - string name = "D:"; - FileSystemItemStatus customStatus = FileSystemItemStatus.Inaccessible; - Result createResult = WindowsRootItem.Create(path, name, customStatus); - Assert.False(createResult.IsFailure); - WindowsRootItem domainModel = createResult.Value; + WindowsRootItem domainModel = _windowsRootItemFixture.Create(path: "D:\\", name: "D:", status: FileSystemItemStatus.Inaccessible); // Act FileSystemTreeNodeResponse result = domainModel.ToTreeNodeResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs index e3ffa525..0bb3e0d9 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/FileSystemManagement/Paths/PathSegmentMappingTests.cs @@ -1,8 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.FileSystemManagement.Paths; using Lumina.Contracts.Responses.FileSystemManagement.Path; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -16,13 +16,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.FileSystemManagement.Paths [ExcludeFromCodeCoverage] public class PathSegmentMappingTests { + private readonly PathSegmentFixture _pathSegmentFixture = new(); + [Fact] public void ToResponse_WhenMappingPathSegment_ShouldMapCorrectly() { // Arrange - Result createResult = PathSegment.Create("TestSegment", true, false); - Assert.False(createResult.IsFailure); - PathSegment pathSegment = createResult.Value; + PathSegment pathSegment = _pathSegmentFixture.Create(name: "TestSegment", isDirectory: true, isDrive: false); // Act PathSegmentResponse result = pathSegment.ToResponse(); @@ -39,9 +39,7 @@ public class PathSegmentMappingTests public void ToResponse_WhenMappingDifferentPathSegmentTypes_ShouldMapCorrectly(string name, bool isDirectory, bool isDrive) { // Arrange - Result createResult = PathSegment.Create(name, isDirectory, isDrive); - Assert.False(createResult.IsFailure); - PathSegment pathSegment = createResult.Value; + PathSegment pathSegment = _pathSegmentFixture.Create(name: name, isDirectory: isDirectory, isDrive: isDrive); // Act PathSegmentResponse result = pathSegment.ToResponse(); @@ -57,10 +55,10 @@ public class PathSegmentMappingTests // Arrange List pathSegments = [ - PathSegment.Create("C:", false, true).Value, - PathSegment.Create("Users", true, false).Value, - PathSegment.Create("Documents", true, false).Value, - PathSegment.Create("file.txt", false, false).Value + _pathSegmentFixture.Create(name: "C:", isDirectory: false, isDrive: true), + _pathSegmentFixture.Create(name: "Users", isDirectory: true, isDrive: false), + _pathSegmentFixture.Create(name: "Documents", isDirectory: true, isDrive: false), + _pathSegmentFixture.Create(name: "file.txt", isDirectory: false, isDrive: false) ]; // Act 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 ddf36d96..0a340076 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 @@ -5,9 +5,9 @@ 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.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -21,24 +21,23 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class LibraryMappingTests { + private readonly LibraryFixture _libraryFixture = new(); + [Fact] public void ToRepositoryEntity_WhenMappingValidLibrary_ShouldMapCorrectly() { // Arrange - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Test Library", - LibraryType.Book, - ["C:/Books", "D:/Media/Books"], - "D:/myPoster.jpg", - true, - false, - true, - false, - false, - [ScanId.CreateUnique()] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/myPoster.jpg", + isEnabled: true, + isLocked: false, + downloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + scanIds: [Guid.NewGuid()]); // Act LibraryEntity result = library.ToRepositoryEntity(); @@ -64,20 +63,11 @@ public class LibraryMappingTests public void ToRepositoryEntity_WhenMappingLibraryWithEmptyContentLocations_ShouldMapCorrectly() { // Arrange - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Empty Library", - LibraryType.Book, - [], - "D:/myPoster.jpg", - true, - false, - true, - false, - false, - [ScanId.CreateUnique()] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Empty Library", + libraryType: LibraryType.Book, + contentLocations: [], + coverImage: "D:/myPoster.jpg"); // Act LibraryEntity result = library.ToRepositoryEntity(); @@ -96,20 +86,15 @@ public class LibraryMappingTests public void ToRepositoryEntity_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Test Library", - libraryType, - ["C:/Media"], - "D:/myPoster.jpg", - true, - false, - true, - false, - false, - [ScanId.CreateUnique()] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: libraryType, + contentLocations: ["C:/Media"], + coverImage: "D:/myPoster.jpg", + isEnabled: true, + isLocked: false, + downloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false); // Act LibraryEntity result = library.ToRepositoryEntity(); @@ -136,20 +121,11 @@ public class LibraryMappingTests "F:/Reading Material" ]; - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Test Library", - LibraryType.Book, - contentLocations, - "D:/myPoster.jpg", - true, - false, - true, - false, - false, - [ScanId.CreateUnique()] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: contentLocations, + coverImage: "D:/myPoster.jpg"); // Act LibraryEntity result = library.ToRepositoryEntity(); @@ -170,20 +146,11 @@ public class LibraryMappingTests "D:/Books" ]; - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Test Library", - LibraryType.Book, - contentLocations, - null, - true, - false, - true, - false, - false, - [ScanId.CreateUnique()] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: contentLocations, + includeCoverImage: false); // Act LibraryEntity result = library.ToRepositoryEntity(); @@ -204,20 +171,12 @@ public class LibraryMappingTests "D:/Books" ]; - Result libraryResult = Library.Create( - UserId.CreateUnique(), - "Test Library", - LibraryType.Book, - contentLocations, - null, - true, - false, - true, - false, - false, - [] - ); - Library library = libraryResult.Value; + Library library = _libraryFixture.Create( + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: contentLocations, + includeCoverImage: false, + scanIds: []); // Act LibraryEntity result = library.ToRepositoryEntity(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs index 315c7a11..159942c5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMappingTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -45,8 +46,8 @@ public class BookMappingTests Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageCode : null, result.OriginalLanguageCode); Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.LanguageName : null, result.OriginalLanguageName); Assert.Equal(book.Metadata.OriginalLanguage.HasValue ? book.Metadata.OriginalLanguage.Value.NativeName.Value : null, result.OriginalLanguageNativeName); - Assert.Equal(book.Metadata.Tags.ToRepositoryEntities(), result.Tags); - Assert.Equal(book.Metadata.Genres.ToRepositoryEntities(), result.Genres); + Assert.Equal(book.Metadata.Tags.ToRepositoryEntities().OrderBy(tag => tag.Name), result.Tags.OrderBy(tag => tag.Name)); + Assert.Equal(book.Metadata.Genres.ToRepositoryEntities().OrderBy(genre => genre.Name), result.Genres.OrderBy(genre => genre.Name)); Assert.Equal(book.Metadata.Publisher.HasValue ? book.Metadata.Publisher.Value : null, result.Publisher); Assert.Equal(book.Metadata.PageCount.HasValue ? book.Metadata.PageCount.Value : null, result.PageCount); Assert.Equal(book.Format.HasValue ? book.Format.Value : null, result.Format); 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 47ee328b..7cbff3fa 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 @@ -2,6 +2,7 @@ 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.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; @@ -19,13 +20,20 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.WrittenConten public class BookMetadataDtoMappingTests { private readonly BookFixture _bookFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); [Fact] public void ApplyMetadata_WhenCalledWithValidMetadata_ShouldApplyItAndMarkTheBookAsEnriched() { // Arrange Book book = _bookFixture.Create(); - BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3"); + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "The Fellowship of the Ring", + description: "The first part of J.R.R. Tolkien's epic adventure.", + goodreadsId: "3", + format: BookFormat.Paperback, + publisher: "Houghton Mifflin", + pageCount: 398); // Act Result result = book.ApplyMetadata(metadata, "Goodreads", DateTime.UtcNow); @@ -47,7 +55,9 @@ public class BookMetadataDtoMappingTests { // Arrange Book book = _bookFixture.Create(); - BookMetadataDto metadata = CreateBookMetadata("The Fellowship of the Ring", "3") with + BookMetadataDto metadata = _bookMetadataDtoFixture.Create( + title: "The Fellowship of the Ring", + goodreadsId: "3") with { Genres = [new GenreDto("")] }; @@ -59,44 +69,4 @@ public class BookMetadataDtoMappingTests Assert.True(result.IsFailure); Assert.Equal(MetadataStatus.Pending, book.MetadataStatus); } - - private static BookMetadataDto CreateBookMetadata(string title, string goodreadsId) - { - return new BookMetadataDto( - Title: title, - OriginalTitle: title, - Description: "The first part of J.R.R. Tolkien's epic adventure.", - ReleaseInfo: new ReleaseInfoDto( - OriginalReleaseDate: new DateOnly(1954, 7, 29), - OriginalReleaseYear: 1954, - ReReleaseDate: null, - ReReleaseYear: null, - ReleaseCountry: "uk", - ReleaseVersion: null - ), - Genres: [new GenreDto("fantasy")], - Tags: [new TagDto("epic fantasy")], - Language: new LanguageInfoDto("en", "English", "English"), - OriginalLanguage: null, - Publisher: "Houghton Mifflin", - PageCount: 398, - Format: BookFormat.Paperback, - Edition: null, - VolumeNumber: 1, - Series: null, - ASIN: null, - GoodreadsId: goodreadsId, - LCCN: null, - OCLCNumber: null, - OpenLibraryId: null, - LibraryThingId: null, - GoogleBooksId: null, - BarnesAndNobleId: null, - AppleBooksId: null, - Isbns: null, - Contributors: null, - Ratings: null, - CoverImageUrl: null - ); - } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs index 5f4f826a..13026483 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Common/IsbnMappingTests.cs @@ -24,7 +24,7 @@ public class IsbnMappingTests public void ToRepositoryEntity_WhenMappingIsbn10_ShouldMapCorrectly() { // Arrange - Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn10); + Isbn isbn = _isbnFixture.Create(format: IsbnFormat.Isbn10); // Act IsbnEntity result = isbn.ToRepositoryEntity(); @@ -39,7 +39,7 @@ public class IsbnMappingTests public void ToRepositoryEntity_WhenMappingIsbn13_ShouldMapCorrectly() { // Arrange - Isbn isbn = _isbnFixture.Create(IsbnFormat.Isbn13); + Isbn isbn = _isbnFixture.Create(format: IsbnFormat.Isbn13); // Act IsbnEntity result = isbn.ToRepositoryEntity(); @@ -56,9 +56,9 @@ public class IsbnMappingTests // Arrange List isbns = [ - _isbnFixture.Create(IsbnFormat.Isbn10), - _isbnFixture.Create(IsbnFormat.Isbn13), - _isbnFixture.Create(IsbnFormat.Isbn10) + _isbnFixture.Create(format: IsbnFormat.Isbn10), + _isbnFixture.Create(format: IsbnFormat.Isbn13), + _isbnFixture.Create(format: IsbnFormat.Isbn10) ]; // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs new file mode 100644 index 00000000..109eeb7c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetLibraryMetadataProvidersRequestMappingTests.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersRequestMappingTests +{ + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetLibraryMetadataProvidersRequest request = new(LibraryId: Guid.NewGuid()); + + // Act + GetLibraryMetadataProvidersQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryId, result.LibraryId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs new file mode 100644 index 00000000..5cdbaef3 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/GetPluginSettingsRequestMappingTests.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsRequestMappingTests +{ + [Fact] + public void ToQuery_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + GetPluginSettingsRequest request = new(PluginId: Guid.NewGuid()); + + // Act + GetPluginSettingsQuery result = request.ToQuery(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.PluginId, result.PluginId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs new file mode 100644 index 00000000..c2e4f3a5 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/LibraryMetadataProviderConfigurationEntityMappingTests.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderConfigurationEntityMappingTests +{ + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidConfiguration_ShouldMapCorrectly() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, pluginId, 3); + + // Act + LibraryMetadataProviderResponse result = configuration.ToResponse("My Provider"); + + // Assert + Assert.NotNull(result); + Assert.Equal(pluginId, result.PluginId); + Assert.Equal("My Provider", result.Name); + Assert.Equal(configuration.IsEnabled, result.IsEnabled); + Assert.Equal(3, result.Rank); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs new file mode 100644 index 00000000..7697c3ba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginEntityMappingTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginEntityMappingTests +{ + private readonly PluginEntityFixture _pluginEntityFixture = new(); + + [Fact] + public void ToResponse_WhenMappingValidPluginEntity_ShouldMapCorrectly() + { + // Arrange + PluginEntity entity = _pluginEntityFixture.Create(); + IReadOnlyDictionary? expectedSettings = JsonSerializer.Deserialize>(entity.SettingsJson!); + + // Act + PluginResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.Id, result.Id); + Assert.Equal(entity.Name, result.Name); + Assert.Equal(entity.Author, result.Author); + Assert.Equal(entity.Version, result.Version); + Assert.Equal(entity.Description, result.Description); + Assert.Equal(entity.LoadStatus, result.LoadStatus); + Assert.Equal(entity.LoadError, result.LoadError); + Assert.Equal(expectedSettings, result.Settings); + } + + [Fact] + public void ToSettings_WhenSettingsAreStored_ShouldDeserializeThem() + { + // Arrange + PluginEntity entity = _pluginEntityFixture.Create(); + + // Act + IReadOnlyDictionary? result = entity.ToSettings(); + + // Assert + Assert.NotNull(result); + Assert.NotEmpty(result); + } + + [Fact] + public void ToSettings_WhenNoSettingsAreStored_ShouldReturnNull() + { + // Arrange + PluginEntity entity = _pluginEntityFixture.Create(); + entity.SettingsJson = null; + + // Act + IReadOnlyDictionary? result = entity.ToSettings(); + + // Assert + Assert.Null(result); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs new file mode 100644 index 00000000..a3a5fee7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/PluginSettingDescriptorMappingTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingDescriptorMappingTests +{ + [Fact] + public void ToResponse_WhenMappingValidDescriptor_ShouldMapCorrectly() + { + // Arrange + PluginSettingDescriptorDto descriptor = new("apiKey", "API Key", PluginSettingType.Text, "default", null); + + // Act + PluginSettingDescriptorResponse result = descriptor.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(descriptor.Key, result.Key); + Assert.Equal(descriptor.Label, result.Label); + Assert.Equal(PluginSettingType.Text, result.Type); + Assert.Equal(descriptor.DefaultValue, result.DefaultValue); + Assert.Null(result.AllowedValues); + } + + [Theory] + [InlineData(PluginSettingType.Text)] + [InlineData(PluginSettingType.Number)] + [InlineData(PluginSettingType.Boolean)] + [InlineData(PluginSettingType.Select)] + public void ToResponse_WhenMappingDifferentSettingTypes_ShouldMapTypeCorrectly(PluginSettingType type) + { + // Arrange + PluginSettingDescriptorDto descriptor = new("key", "Label", type, null, null); + + // Act + PluginSettingDescriptorResponse result = descriptor.ToResponse(); + + // Assert + Assert.Equal(type, result.Type); + } + + [Fact] + public void ToResponse_WhenMappingDescriptorWithAllowedValues_ShouldMapAllowedValues() + { + // Arrange + PluginSettingDescriptorDto descriptor = new("mode", "Mode", PluginSettingType.Select, null, ["fast", "slow"]); + + // Act + PluginSettingDescriptorResponse result = descriptor.ToResponse(); + + // Assert + Assert.NotNull(result.AllowedValues); + Assert.Equal(2, result.AllowedValues.Count); + Assert.Equal("fast", result.AllowedValues[0]); + Assert.Equal("slow", result.AllowedValues[1]); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs new file mode 100644 index 00000000..6a56ddcd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/ReorderLibraryMetadataProvidersRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersRequestMappingTests +{ + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + ReorderLibraryMetadataProvidersRequest request = new(LibraryId: Guid.NewGuid(), PluginIds: [Guid.NewGuid(), Guid.NewGuid()]); + + // Act + ReorderLibraryMetadataProvidersCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryId, result.LibraryId); + Assert.Equal(request.PluginIds, result.PluginIds); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs new file mode 100644 index 00000000..474efa4e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/SetLibraryMetadataProviderEnabledRequestMappingTests.cs @@ -0,0 +1,32 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledRequestMappingTests +{ + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + SetLibraryMetadataProviderEnabledRequest request = new(LibraryId: Guid.NewGuid(), PluginId: Guid.NewGuid(), IsEnabled: true); + + // Act + SetLibraryMetadataProviderEnabledCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.LibraryId, result.LibraryId); + Assert.Equal(request.PluginId, result.PluginId); + Assert.Equal(request.IsEnabled, result.IsEnabled); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs new file mode 100644 index 00000000..1c08cf99 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Plugins/UpdatePluginSettingsRequestMappingTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsRequestMappingTests +{ + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + UpdatePluginSettingsRequest request = new(PluginId: Guid.NewGuid(), Settings: new Dictionary { ["key"] = "value" }); + + // Act + UpdatePluginSettingsCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.PluginId, result.PluginId); + Assert.Equal(request.Settings, result.Settings); + } + + [Fact] + public void ToCommand_WhenMappingRequestWithNullSettings_ShouldMapNullSettings() + { + // Arrange + UpdatePluginSettingsRequest request = new(PluginId: Guid.NewGuid(), Settings: null); + + // Act + UpdatePluginSettingsCommand result = request.ToCommand(); + + // Assert + Assert.Null(result.Settings); + } +} 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 984778cc..1b398857 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 @@ -6,7 +6,7 @@ using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookL using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; -using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -20,14 +20,13 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UserManagement.Users; [ExcludeFromCodeCoverage] public class UserMappingTests { + private readonly UserFixture _userFixture = new(); + [Fact] public void ToRepositoryEntity_WhenMappingValidUser_ShouldOnlyUpdateUsername() { // Arrange - User domainEntity = User.Create( - UserId.Create(Guid.NewGuid()), - "newusername" - ).Value; + User domainEntity = _userFixture.Create(username: "newusername"); UserEntity repositoryEntity = new() { @@ -72,10 +71,7 @@ public class UserMappingTests public void ToRepositoryEntity_WhenMappingDifferentUsernames_ShouldUpdateCorrectly(string newUsername) { // Arrange - User domainEntity = User.Create( - UserId.Create(Guid.NewGuid()), - newUsername - ).Value; + User domainEntity = _userFixture.Create(username: newUsername); UserEntity repositoryEntity = new() { @@ -102,10 +98,7 @@ public class UserMappingTests public void ToRepositoryEntity_WhenRepositoryEntityHasLibraries_ShouldPreserveLibraries() { // Arrange - User domainEntity = User.Create( - UserId.Create(Guid.NewGuid()), - "newusername" - ).Value; + User domainEntity = _userFixture.Create(username: "newusername"); List libraries = [ 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 new file mode 100644 index 00000000..52e66af8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsRequestMappingTests +{ + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false); + + // Act + UpdateUserSettingsCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled); + Assert.Equal(request.ItemsPerPage, result.ItemsPerPage); + Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + } +} 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 new file mode 100644 index 00000000..5ac4822a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsEntityMappingTests +{ + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingValidRepositoryEntity_ShouldMapCorrectly() + { + // Arrange + UserSettingsEntity entity = _userSettingsEntityFixture.Create(); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(entity.Id, result.Value.Id.Value); + Assert.Equal(entity.UserId, result.Value.UserId.Value); + Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled); + Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage); + Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public void ToResponse_WhenMappingValidRepositoryEntity_ShouldMapCorrectly() + { + // Arrange + UserSettingsEntity entity = _userSettingsEntityFixture.Create(); + + // Act + UserSettingsResponse result = entity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(entity.UserId, result.UserId); + Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled); + Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage); + Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + } +} 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 new file mode 100644 index 00000000..a9241202 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsMappingTests +{ + private readonly UserSettingsFixture _userSettingsFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingValidDomainEntity_ShouldMapCorrectly() + { + // Arrange + Guid userId = Guid.NewGuid(); + UserSettings domainEntity = _userSettingsFixture.Create(userId: userId); + + // Act + UserSettingsEntity result = domainEntity.ToRepositoryEntity(); + + // Assert + Assert.NotNull(result); + Assert.Equal(domainEntity.Id.Value, result.Id); + Assert.Equal(userId, result.UserId); + Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); + Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); + Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + } + + [Fact] + public void ToResponse_WhenMappingValidDomainEntity_ShouldMapCorrectly() + { + // Arrange + Guid userId = Guid.NewGuid(); + UserSettings domainEntity = _userSettingsFixture.Create(userId: userId); + + // Act + UserSettingsResponse result = domainEntity.ToResponse(); + + // Assert + Assert.NotNull(result); + Assert.Equal(userId, result.UserId); + Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); + Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); + Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/TaskUtilitiesTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/TaskUtilitiesTests.cs new file mode 100644 index 00000000..0d75602d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/TaskUtilitiesTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Utilities; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TaskUtilitiesTests +{ + [Fact] + public async Task FireAndForgetSafeAsync_WhenTaskCompletesSuccessfully_ShouldInvokeOnComplete() + { + // Arrange + TaskCompletionSource completionSource = new(); + bool onCompleteInvoked = false; + + // Act + Task.CompletedTask.FireAndForgetSafeAsync(() => + { + onCompleteInvoked = true; + completionSource.SetResult(true); + }); + + // Assert + await completionSource.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.True(onCompleteInvoked); + } + + [Fact] + public async Task FireAndForgetSafeAsync_WhenTaskFaults_ShouldSwallowExceptionAndInvokeOnComplete() + { + // Arrange + TaskCompletionSource completionSource = new(); + bool onCompleteInvoked = false; + Task faultedTask = Task.FromException(new InvalidOperationException("Expected failure")); + + // Act + faultedTask.FireAndForgetSafeAsync(() => + { + onCompleteInvoked = true; + completionSource.SetResult(true); + }); + + // Assert + await completionSource.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.True(onCompleteInvoked); + } + + [Fact] + public async Task FireAndForgetSafeAsync_WhenTaskIsCanceled_ShouldSwallowExceptionAndInvokeOnComplete() + { + // Arrange + TaskCompletionSource completionSource = new(); + bool onCompleteInvoked = false; + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + Task canceledTask = Task.FromCanceled(cancellationTokenSource.Token); + + // Act + canceledTask.FireAndForgetSafeAsync(() => + { + onCompleteInvoked = true; + completionSource.SetResult(true); + }); + + // Assert + await completionSource.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.True(onCompleteInvoked); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs new file mode 100644 index 00000000..c0d3c668 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Utilities/ValidatorUtilitiesTests.cs @@ -0,0 +1,810 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Common.Utilities; +using Lumina.Application.Fixtures.Common.Utilities; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValidatorUtilitiesTests +{ + private readonly ValidatorUtilitiesTestValidator _validator = new(); + private readonly ValidatorUtilitiesTestRequestFixture _validatorUtilitiesTestRequestFixture = new(); + + [Fact] + public void Validate_WhenRequestIsFullyValid_ShouldNotHaveAnyValidationErrors() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Theory] + [InlineData(4)] // value is greater than the comparison value + [InlineData(100)] // value is much greater than the comparison value + public void Validate_WhenIntValueIsGreaterThanComparison_ShouldNotHaveValidationError(int value) + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { IntValue = value }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_intValueError); + } + + [Theory] + [InlineData(3)] // value equals the comparison value + [InlineData(1)] // value is smaller than the comparison value + [InlineData(-5)] // value is negative and smaller than the comparison value + public void Validate_WhenIntValueIsNotGreaterThanComparison_ShouldHaveValidationError(int value) + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { IntValue = value }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_intValueError); + } + + [Fact] + public void Validate_WhenNullableIntValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableIntValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableIntValueError); + } + + [Fact] + public void Validate_WhenNullableIntValueIsNotGreaterThanComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableIntValue = 2 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableIntValueError); + } + + [Fact] + public void Validate_WhenDecimalValueIsNotGreaterThanComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { DecimalValue = 3m }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_decimalValueError); + } + + [Fact] + public void Validate_WhenNullableDecimalValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableDecimalValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDecimalValueError); + } + + [Fact] + public void Validate_WhenNullableDecimalValueIsNotGreaterThanComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableDecimalValue = 2m }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableDecimalValueError); + } + + [Fact] + public void Validate_WhenTimeSpanValueIsNotGreaterThanComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { TimeSpanValue = TimeSpan.FromHours(3) }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_timeSpanValueError); + } + + [Fact] + public void Validate_WhenIntValue2IsEqual_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { IntValue2 = 5 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_intValue2Error); + } + + [Fact] + public void Validate_WhenIntValue2IsSmaller_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { IntValue2 = 4 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_intValue2Error); + } + + [Fact] + public void Validate_WhenNullableIntValue2IsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableIntValue2 = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableIntValue2Error); + } + + [Fact] + public void Validate_WhenNullableIntValue2IsSmaller_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableIntValue2 = 4 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableIntValue2Error); + } + + [Fact] + public void Validate_WhenNullableDecimalValue2IsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableDecimalValue2 = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableDecimalValue2Error); + } + + [Fact] + public void Validate_WhenNullableDecimalValue2IsSmaller_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableDecimalValue2 = 4m }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableDecimalValue2Error); + } + + [Fact] + public void Validate_WhenNotNullValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotNullValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_notNullValueError); + } + + [Fact] + public void Validate_WhenNotNullValueIsNotNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_notNullValueError); + } + + [Theory] + [InlineData(null)] // null string + [InlineData("")] // empty string + [InlineData(" ")] // white-space only string + public void Validate_WhenNotEmptyValueIsEmpty_ShouldHaveValidationError(string? value) + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyValue = value }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_notEmptyValueError); + } + + [Fact] + public void Validate_WhenNotEmptyValueIsNotBlank_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyValue = "value" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_notEmptyValueError); + } + + [Fact] + public void Validate_WhenNotEmptyGuidValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyGuidValue = Guid.Empty }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_notEmptyGuidValueError); + } + + [Fact] + public void Validate_WhenNotEmptyCollectionValueIsEmpty_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyCollectionValue = [] }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_notEmptyCollectionValueError); + } + + [Fact] + public void Validate_WhenNotEmptyCollectionValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyCollectionValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_notEmptyCollectionValueError); + } + + [Fact] + public void Validate_WhenNotEmptyCollectionValueHasItems_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NotEmptyCollectionValue = ["item"] }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_notEmptyCollectionValueError); + } + + [Fact] + public void Validate_WhenEnumValueIsNotDefined_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { EnumValue = (ValidatorUtilitiesTestEnum)99 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_enumValueError); + } + + [Fact] + public void Validate_WhenEnumValueIsDefined_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { EnumValue = ValidatorUtilitiesTestEnum.First }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_enumValueError); + } + + [Fact] + public void Validate_WhenNullableEnumValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableEnumValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableEnumValueError); + } + + [Fact] + public void Validate_WhenNullableEnumValueIsNotDefined_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableEnumValue = (ValidatorUtilitiesTestEnum)99 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_nullableEnumValueError); + } + + [Fact] + public void Validate_WhenNullableEnumValueIsDefined_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { NullableEnumValue = ValidatorUtilitiesTestEnum.First }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_nullableEnumValueError); + } + + [Fact] + public void Validate_WhenMaxLengthValueExceedsMaximumLength_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MaxLengthValue = "abcdef" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_maxLengthValueError); + } + + [Fact] + public void Validate_WhenMaxLengthValueIsAtMaximumLength_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MaxLengthValue = "abcde" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_maxLengthValueError); + } + + [Fact] + public void Validate_WhenMaxLengthValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MaxLengthValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_maxLengthValueError); + } + + [Fact] + public void Validate_WhenMinLengthValueIsBelowMinimumLength_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MinLengthValue = "ab" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_minLengthValueError); + } + + [Fact] + public void Validate_WhenMinLengthValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MinLengthValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_minLengthValueError); + } + + [Fact] + public void Validate_WhenMinLengthValueIsAtMinimumLength_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MinLengthValue = "abc" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_minLengthValueError); + } + + [Fact] + public void Validate_WhenExactLengthValueDoesNotMatchExactLength_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { ExactLengthValue = "ab" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_exactLengthValueError); + } + + [Fact] + public void Validate_WhenExactLengthValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { ExactLengthValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_exactLengthValueError); + } + + [Fact] + public void Validate_WhenExactLengthValueMatchesExactLength_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { ExactLengthValue = "abc" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_exactLengthValueError); + } + + [Fact] + public void Validate_WhenRangeLengthValueIsOutsideRange_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { RangeLengthValue = "abcdef" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_rangeLengthValueError); + } + + [Fact] + public void Validate_WhenRangeLengthValueIsNull_ShouldHaveValidationErrorForRange() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { RangeLengthValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_rangeLengthValueError); + } + + [Fact] + public void Validate_WhenRangeLengthValueIsWithinRange_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { RangeLengthValue = "abcd" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_rangeLengthValueError); + } + + [Fact] + public void Validate_WhenMatchValueDoesNotMatchPattern_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MatchValue = "not-a-match" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_matchValueError); + } + + [Fact] + public void Validate_WhenMatchValueIsNull_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MatchValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_matchValueError); + } + + [Fact] + public void Validate_WhenMatchValueMatchesPattern_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { MatchValue = "abc-123" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_matchValueError); + } + + [Fact] + public void Validate_WhenSelectorMatchValueDoesNotMatchSelectedPattern_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { SelectorMatchValue = "invalid" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_selectorMatchValueError); + } + + [Fact] + public void Validate_WhenSelectorMatchValueMatchesSelectedPattern_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { SelectorMatchValue = "xyz-999" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_selectorMatchValueError); + } + + [Fact] + public void Validate_WhenInclusiveIntValueIsBelowMinimum_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { InclusiveIntValue = 0 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_inclusiveIntValueError); + } + + [Fact] + public void Validate_WhenInclusiveIntValueIsAboveMaximum_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { InclusiveIntValue = 11 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_inclusiveIntValueError); + } + + [Fact] + public void Validate_WhenInclusiveIntValueIsWithinRange_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { InclusiveIntValue = 1 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_inclusiveIntValueError); + } + + [Fact] + public void Validate_WhenInclusiveNullableIntValueIsNull_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { InclusiveNullableIntValue = null }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_inclusiveNullableIntValueError); + } + + [Fact] + public void Validate_WhenInclusiveNullableIntValueIsOutsideRange_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { InclusiveNullableIntValue = 12 }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_inclusiveNullableIntValueError); + } + + [Fact] + public void Validate_WhenEqualValueDiffersFromComparison_ShouldHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + request = request with { EqualValue = "different" }; + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldHaveValidationError(s_equalValueError); + } + + [Fact] + public void Validate_WhenEqualValueEqualsComparison_ShouldNotHaveValidationError() + { + // Arrange + ValidatorUtilitiesTestRequest request = _validatorUtilitiesTestRequestFixture.Create(); + + // Act + List result = _validator.TestValidate(request); + + // Assert + result.ShouldNotHaveValidationError(s_equalValueError); + } + + [ExcludeFromCodeCoverage] + private sealed class ValidatorUtilitiesTestValidator : AbstractValidator + { + public ValidatorUtilitiesTestValidator() + { + RuleFor(request => request.IntValue).GreaterThan(3).WithError(s_intValueError); + RuleFor(request => request.NullableIntValue).GreaterThan(3).WithError(s_nullableIntValueError); + RuleFor(request => request.DecimalValue).GreaterThan(3m).WithError(s_decimalValueError); + RuleFor(request => request.NullableDecimalValue).GreaterThan(3m).WithError(s_nullableDecimalValueError); + RuleFor(request => request.TimeSpanValue).GreaterThan(TimeSpan.FromHours(3)).WithError(s_timeSpanValueError); + RuleFor(request => request.IntValue2).GreaterThanOrEqualTo(5).WithError(s_intValue2Error); + RuleFor(request => request.NullableIntValue2).GreaterThanOrEqualTo(5).WithError(s_nullableIntValue2Error); + RuleFor(request => request.NullableDecimalValue2).GreaterThanOrEqualTo(5m).WithError(s_nullableDecimalValue2Error); + RuleFor(request => request.NotNullValue).NotNull().WithError(s_notNullValueError); + RuleFor(request => request.NotEmptyValue).NotEmpty().WithError(s_notEmptyValueError); + RuleFor(request => request.NotEmptyGuidValue).NotEmpty().WithError(s_notEmptyGuidValueError); + RuleFor(request => request.NotEmptyCollectionValue).NotEmpty().WithError(s_notEmptyCollectionValueError); + RuleFor(request => request.EnumValue).IsInEnum().WithError(s_enumValueError); + RuleFor(request => request.NullableEnumValue).IsInEnum().WithError(s_nullableEnumValueError); + RuleFor(request => request.MaxLengthValue).MaximumLength(5).WithError(s_maxLengthValueError); + RuleFor(request => request.MinLengthValue).MinimumLength(3).WithError(s_minLengthValueError); + RuleFor(request => request.ExactLengthValue).Length(3).WithError(s_exactLengthValueError); + RuleFor(request => request.RangeLengthValue).Length(3, 5).WithError(s_rangeLengthValueError); + RuleFor(request => request.MatchValue).Matches("^[a-z]{3}-\\d{3}$").WithError(s_matchValueError); + RuleFor(request => request.SelectorMatchValue).Matches(instance => instance.PatternValue).WithError(s_selectorMatchValueError); + RuleFor(request => request.InclusiveIntValue).InclusiveBetween(1, 10).WithError(s_inclusiveIntValueError); + RuleFor(request => request.InclusiveNullableIntValue).InclusiveBetween(1, 10).WithError(s_inclusiveNullableIntValueError); + RuleFor(request => request.EqualValue).Equal(instance => instance.EqualComparisonValue).WithError(s_equalValueError); + } + } + + private static readonly Error s_intValueError = Error.Validation(description: "IntValueError"); + private static readonly Error s_nullableIntValueError = Error.Validation(description: "NullableIntValueError"); + private static readonly Error s_decimalValueError = Error.Validation(description: "DecimalValueError"); + private static readonly Error s_nullableDecimalValueError = Error.Validation(description: "NullableDecimalValueError"); + private static readonly Error s_timeSpanValueError = Error.Validation(description: "TimeSpanValueError"); + private static readonly Error s_intValue2Error = Error.Validation(description: "IntValue2Error"); + private static readonly Error s_nullableIntValue2Error = Error.Validation(description: "NullableIntValue2Error"); + private static readonly Error s_nullableDecimalValue2Error = Error.Validation(description: "NullableDecimalValue2Error"); + private static readonly Error s_notNullValueError = Error.Validation(description: "NotNullValueError"); + private static readonly Error s_notEmptyValueError = Error.Validation(description: "NotEmptyValueError"); + private static readonly Error s_notEmptyGuidValueError = Error.Validation(description: "NotEmptyGuidValueError"); + private static readonly Error s_notEmptyCollectionValueError = Error.Validation(description: "NotEmptyCollectionValueError"); + private static readonly Error s_enumValueError = Error.Validation(description: "EnumValueError"); + private static readonly Error s_nullableEnumValueError = Error.Validation(description: "NullableEnumValueError"); + private static readonly Error s_maxLengthValueError = Error.Validation(description: "MaxLengthValueError"); + private static readonly Error s_minLengthValueError = Error.Validation(description: "MinLengthValueError"); + private static readonly Error s_exactLengthValueError = Error.Validation(description: "ExactLengthValueError"); + private static readonly Error s_rangeLengthValueError = Error.Validation(description: "RangeLengthValueError"); + private static readonly Error s_matchValueError = Error.Validation(description: "MatchValueError"); + private static readonly Error s_selectorMatchValueError = Error.Validation(description: "SelectorMatchValueError"); + private static readonly Error s_inclusiveIntValueError = Error.Validation(description: "InclusiveIntValueError"); + private static readonly Error s_inclusiveNullableIntValueError = Error.Validation(description: "InclusiveNullableIntValueError"); + private static readonly Error s_equalValueError = Error.Validation(description: "EqualValueError"); +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs index 1acaa59b..9787699a 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using NSubstitute; using System.Collections.Generic; @@ -26,6 +27,7 @@ public class GetDrivesQueryHandlerTests private readonly IDriveService _mockDriveService; private readonly GetDrivesQueryHandler _sut; private readonly GetDrivesQueryFixture _getDrivesQueryFixture = new(); + private readonly WindowsRootItemFixture _windowsRootItemFixture = new(); /// /// Initializes a new instance of the class. @@ -44,8 +46,8 @@ public class GetDrivesQueryHandlerTests IEnumerable drives = [ - WindowsRootItem.Create("C:\\", "C:").Value, - WindowsRootItem.Create("D:\\", "D:").Value + _windowsRootItemFixture.Create(path: "C:\\", name: "C:"), + _windowsRootItemFixture.Create(path: "D:\\", name: "D:") ]; _mockDriveService.GetDrives() diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs new file mode 100644 index 00000000..12cb29bf --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -0,0 +1,268 @@ +#region ========================================================================= USING ===================================================================================== +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; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Contracts.Responses.MediaLibrary.Management; +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.Events; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.AddLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IValidator _mockValidator; + private readonly AddLibraryCommandHandler _sut; + private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public AddLibraryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockEnvironmentContext = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated, is an admin, and the cover image is a valid image + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + _mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValid_ShouldInsertLibraryAndReturnResponse() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(persistedLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(persistedLibrary.Id, result.Value.Id); + await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImageIsNull_ShouldSkipImageTypeCheck() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { CoverImage = null }; + LibraryEntity persistedLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(persistedLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImageIsNotAnImage_ShouldReturnCoverFileMustBeAnImageError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenImageTypeCheckFails_ShouldReturnError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to determine image type")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImagePathIsInvalid_ShouldReturnInvalidPathError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { CoverImage = " " }; + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdminAndLacksPermission_ShouldReturnNotAuthorizedError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryCreationFails_ShouldReturnError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + command = command with { ContentLocations = [""] }; + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to insert library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCreatedLibraryCannotBeRetrieved_ShouldReturnPersistenceError() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.ErrorPersistingMediaLibrary, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs new file mode 100644 index 00000000..20333317 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibrariesScan/CancelLibrariesScanCommandHandlerTests.cs @@ -0,0 +1,172 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly CancelLibrariesScanCommandHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public CancelLibrariesScanCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and is an admin + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new CancelLibrariesScanCommandHandler(_mockCurrentUserService, _mockAuthorizationService, _mockDomainEventsQueue, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldCancelAllRunningScans() + { + // Arrange + List runningScans = + [ + _libraryScanEntityFixture.Create(userId: _userId), + _libraryScanEntityFixture.Create(userId: _userId) + ]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + await _mockLibraryScanRepository.Received(2).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(2).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyCancelScansOwnedByTheUser() + { + // Arrange + Guid otherUserId = Guid.NewGuid(); + List runningScans = + [ + _libraryScanEntityFixture.Create(userId: _userId), + _libraryScanEntityFixture.Create(userId: otherUserId) + ]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockLibraryScanRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().GetRunningScansAsync(Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError() + { + // Arrange + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get running scans")); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnError() + { + // Arrange + List runningScans = [_libraryScanEntityFixture.Create(userId: _userId)]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to update library scan")); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError() + { + // Arrange + List runningScans = [_libraryScanEntityFixture.Create(userId: _userId, status: LibraryScanJobStatus.Completed)]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + + // Act + Result result = await _sut.HandleAsync(new CancelLibrariesScanCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs new file mode 100644 index 00000000..6c9d3a7e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/CancelLibraryScan/CancelLibraryScanCommandHandlerTests.cs @@ -0,0 +1,219 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Commands.CancelLibraryScan; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.CancelLibraryScan; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +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; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.CancelLibraryScan; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IValidator _mockValidator; + private readonly CancelLibraryScanCommandHandler _sut; + private readonly CancelLibraryScanCommandFixture _cancelLibraryScanCommandFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public CancelLibraryScanCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the ownership policy allows the cancellation + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new CancelLibraryScanCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenRunningScanExists_ShouldCancelScanAndReturnSuccess() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Result.From(runningScan)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + await _mockLibraryScanRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get library scan")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Result.From(runningScan)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanIsNotRunning_ShouldReturnError() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId, status: LibraryScanJobStatus.Completed); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Result.From(completedScan)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(id: command.ScanId, libraryId: command.LibraryId, userId: _userId); + _mockLibraryScanRepository.GetByIdAsync(command.ScanId, Arg.Any()) + .Returns(Result.From(runningScan)); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to update library scan")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + CancelLibraryScanCommand command = _cancelLibraryScanCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs new file mode 100644 index 00000000..bfa3ce45 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Commands.DeleteLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.DeleteLibrary; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.DeleteLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IValidator _mockValidator; + private readonly DeleteLibraryCommandHandler _sut; + private readonly DeleteLibraryCommandFixture _deleteLibraryCommandFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the ownership policy allows the deletion + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new DeleteLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryExists_ShouldDeleteLibraryAndReturnDeleted() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDomainConversionFails_ShouldReturnError() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenDeleteByIdFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockLibraryRepository.DeleteByIdAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to delete library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} 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 new file mode 100644 index 00000000..a402d079 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibraries/ScanLibrariesCommandHandlerTests.cs @@ -0,0 +1,225 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +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 DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.ScanLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly ScanLibrariesCommandHandler _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public ScanLibrariesCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and is an admin + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + _sut = new ScanLibrariesCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldStartScansForAllEnabledAndUnlockedLibraries() + { + // Arrange + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: _userId) + ]; + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count()); + Assert.Equal(libraries[0].Id, result.Value.First().LibraryId); + Assert.Equal(libraries[1].Id, result.Value.ElementAt(1).LibraryId); + await _mockLibraryScanRepository.Received(2).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(2).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldOnlyStartScansForLibrariesOwnedByTheUser() + { + // Arrange + Guid otherUserId = Guid.NewGuid(); + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: otherUserId) + ]; + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + MediaLibraryScanResponse response = Assert.Single(result.Value); + Assert.Equal(libraries[0].Id, response.LibraryId); + await _mockLibraryScanRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetAllEnabledAndUnlockedAsync(Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllEnabledAndUnlockedFails_ShouldReturnError() + { + // Arrange + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get libraries")); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsAlreadyBeingScanned_ShouldSkipThatLibraryAndContinue() + { + // Arrange + LibraryEntity firstLibrary = _libraryEntityFixture.Create(userId: _userId); + LibraryEntity secondLibrary = _libraryEntityFixture.Create(userId: _userId); + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()) + .Returns(Result.From>([firstLibrary, secondLibrary])); + + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: firstLibrary.Id, userId: _userId, status: Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary.LibraryScanJobStatus.Running); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(firstLibrary.Id, Arg.Any()) + .Returns(Result.From>([runningScan])); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + MediaLibraryScanResponse response = Assert.Single(result.Value); + Assert.Equal(secondLibrary.Id, response.LibraryId); + await _mockLibraryScanRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldReturnError() + { + // Arrange + List libraries = [_libraryEntityFixture.Create(userId: _userId)]; + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to insert library scan")); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPastMonthScansRetrievalFails_ShouldReturnError() + { + // Arrange + List libraries = [_libraryEntityFixture.Create(userId: _userId)]; + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to get past month scans")); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDomainConversionFails_ShouldReturnError() + { + // Arrange + List libraries = [_libraryEntityFixture.Create(userId: _userId, contentLocations: [""])]; + _mockLibraryRepository.GetAllEnabledAndUnlockedAsync(Arg.Any()).Returns(Result.From>(libraries)); + + // Act + Result> result = await _sut.HandleAsync(new ScanLibrariesCommand(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs new file mode 100644 index 00000000..66b45d40 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/ScanLibrary/ScanLibraryCommandHandlerTests.cs @@ -0,0 +1,306 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Commands.ScanLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.ScanLibrary; +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 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; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.ScanLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IValidator _mockValidator; + private readonly ScanLibraryCommandHandler _sut; + private readonly ScanLibraryCommandFixture _scanLibraryCommandFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public ScanLibraryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the ownership policy allows the scan + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new ScanLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsEnabledAndUnlocked_ShouldQueueScanAndReturnResponse() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(command.Id, result.Value.LibraryId); + await _mockLibraryScanRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsDisabled_ShouldReturnCannotScanDisabledLibraryError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isEnabled: false); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.CannotScanDisabledLibrary, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsLocked_ShouldReturnCannotScanLockedLibraryError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, isLocked: true); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.CannotScanLockedLibrary, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDomainConversionFails_ShouldReturnError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId, contentLocations: [""]); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPastMonthScansRetrievalFails_ShouldReturnError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get past month scans")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsAlreadyBeingScanned_ShouldReturnError() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(libraryId: command.Id, userId: _userId, status: LibraryScanJobStatus.Running); + _mockLibraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, Arg.Any()) + .Returns(Result.From>([runningScan])); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockLibraryScanRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to insert library scan")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + ScanLibraryCommand command = _scanLibraryCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryScanRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs new file mode 100644 index 00000000..e529d69e --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -0,0 +1,334 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.Commands.UpdateLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Commands.UpdateLibrary; +using Lumina.Contracts.Responses.MediaLibrary.Management; +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.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Commands.UpdateLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IValidator _mockValidator; + private readonly UpdateLibraryCommandHandler _sut; + private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public UpdateLibraryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockEnvironmentContext = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated, has the manage permission, and the cover image is a valid image + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCommandIsValid_ShouldUpdateLibraryAndReturnResponse() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(existingLibrary.Id, result.Value.Id); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImageIsNull_ShouldSkipImageTypeCheck() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = null }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImageIsNotAnImage_ShouldReturnCoverFileMustBeAnImageError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenImageTypeCheckFails_ShouldReturnError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to determine image type")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverImagePathIsInvalid_ShouldReturnInvalidPathError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = " " }; + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserLacksPermissionAndPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryCreationFails_ShouldReturnError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); + command = command with { ContentLocations = [""] }; + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to update library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetCreatedLibraryFails_ShouldReturnError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary), Error.Failure(description: "Failed to retrieve updated library")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task HandleAsync_WhenCreatedLibraryCannotBeRetrieved_ShouldReturnPersistenceError() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary), Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Persistence.ErrorPersistingMediaLibrary, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs new file mode 100644 index 00000000..940b7ed9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryDeletedDomainEventHandlerTests.cs @@ -0,0 +1,112 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Domain.Common.Exceptions; +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.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryDeletedDomainEventHandlerTests +{ + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly LibraryDeletedDomainEventHandler _sut; + private readonly LibraryFixture _libraryFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryDeletedDomainEventHandlerTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + _mockPathService = Substitute.For(); + + MediaSettingsDto mediaSettings = new() + { + RootDirectory = "Media", + LibrariesDirectory = "Libraries" + }; + IOptions mediaSettingsOptions = Substitute.For>(); + mediaSettingsOptions.Value.Returns(mediaSettings); + + // default stubs: all path combinations succeed and the directory is deleted successfully + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockDirectoryProviderService.DeleteDirectory(Arg.Any()).Returns(Result.Deleted); + + _sut = new LibraryDeletedDomainEventHandler(_mockEnvironmentContext, _mockPathService, mediaSettingsOptions); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIsDeleted_ShouldDeleteLibraryDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockDirectoryProviderService.Received(1).DeleteDirectory( + Arg.Is(path => path.Path.EndsWith(libraryId.ToString(), StringComparison.Ordinal))); + } + + [Fact] + public async Task HandleAsync_WhenDeleteDirectoryFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to delete library directory"); + _mockDirectoryProviderService.DeleteDirectory(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + } + + [Fact] + public async Task HandleAsync_WhenGetLibraryPathFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId); + LibraryDeletedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to combine path"); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + _mockDirectoryProviderService.DidNotReceive().DeleteDirectory(Arg.Any()); + } +} 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 new file mode 100644 index 00000000..e53e7369 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -0,0 +1,253 @@ +#region ========================================================================= USING ===================================================================================== +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.Infrastructure.Models.DTO.Configuration; +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.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.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Microsoft.Extensions.Options; +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; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibrarySavedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IFileTypeService _mockFileTypeService; + private readonly IPathService _mockPathService; + private readonly LibrarySavedDomainEventHandler _sut; + private readonly LibraryFixture _libraryFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibrarySavedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockEnvironmentContext = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockPathService = Substitute.For(); + + MediaSettingsDto mediaSettings = new() + { + RootDirectory = "Media", + LibrariesDirectory = "Libraries" + }; + IOptions mediaSettingsOptions = Substitute.For>(); + mediaSettingsOptions.Value.Returns(mediaSettings); + + // default stubs: the cover source file exists and is a valid image, the library directory does not exist yet, and all path combinations succeed + _mockPathService.PathSeparator.Returns('/'); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.PNG)); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(false)); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(Result.From(_fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid"))); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/cover.png"))); + _mockFileProviderService.RenameFile(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(path: string.Concat(AppContext.BaseDirectory, "libraries/guid/", callInfo.ArgAt(1))))); + _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new LibrarySavedDomainEventHandler(_mockUnitOfWork, _mockEnvironmentContext, _mockPathService, mediaSettingsOptions); + } + + [Fact] + public async Task HandleAsync_WhenLibraryHasCoverImage_ShouldCopyCoverToMediaDirectoryAndUpdateLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + LibraryEntity updatedLibrary = _libraryEntityFixture.Create(id: libraryId); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + Assert.NotNull(library.CoverImage); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryCoverDirectoryExists_ShouldDeletePreviousCoversAndCopyNewCover() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()).Returns(Result.From(true)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>( + [ + _fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/cover.jpg"), + _fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/notes.txt") + ])); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + FileSystemPathId coverFile = _fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/cover.jpg"); + _mockFileProviderService.Received(2).DeleteFile(coverFile); + _mockFileProviderService.DidNotReceive().DeleteFile(_fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/notes.txt")); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryHasNoCoverImage_ShouldDeleteExistingCoverFromMediaDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>( + [ + _fileSystemPathIdFixture.Create(path: "C:/Media/Libraries/guid/cover.png") + ])); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockFileProviderService.Received(1).DeleteFile(Arg.Any()); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverSourceFileDoesNotExist_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.FileSystemManagement.FileNotFound, exception.EventualConsistencyError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCoverFileIsNotAnImage_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, exception.EventualConsistencyError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCopyFileFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to copy cover file"); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockLibraryRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetLibraryPathFailsForLibraryWithoutCover_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, includeCoverImage: false); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to combine path"); + _mockPathService.CombinePath(Arg.Any(), Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + _mockFileProviderService.DidNotReceive().DeleteFile(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "C:/Users/user/cover.jpg"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to update library"); + _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs new file mode 100644 index 00000000..8833f45b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanCancelledDomainEventHandlerTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +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.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using 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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanCancelledDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository; + private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService; + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker; + private readonly LibraryScanCancelledDomainEventHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanCancelledDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockLibraryScanStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository); + _mockMediaLibraryScanningService = Substitute.For(); + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockMediaLibrariesScanCancellationTracker = Substitute.For(); + + // default stubs: the cancellation service and the staging results clearing succeed + _mockMediaLibraryScanningService.CancelScan(Arg.Any()).Returns(Result.Success); + _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new LibraryScanCancelledDomainEventHandler(_mockMediaLibraryScanningService, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibrariesScanProgressTracker, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScanExists_ShouldCancelScanAndCleanupResources() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockMediaLibraryScanningService.Received(1).CancelScan(Arg.Is(libraryScan => libraryScan.Id.Value == scan.Id)); + _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(Arg.Any()); + _mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(Arg.Any()); + await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to get library scan"); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() + { + // Arrange + LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); + await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCancelScanFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + Error error = Error.Failure(description: "Failed to cancel scan"); + _mockMediaLibraryScanningService.CancelScan(Arg.Any()).Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + _mockMediaLibrariesScanCancellationTracker.DidNotReceive().RemoveScan(Arg.Any()); + await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + LibraryScanCancelledDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + Error error = Error.Failure(description: "Failed to clear staging results"); + _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs new file mode 100644 index 00000000..aa5de98a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFailedDomainEventHandlerTests.cs @@ -0,0 +1,204 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +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; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFailedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly ILibraryScanStagingResultsRepository _mockLibraryScanStagingResultsRepository; + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker; + private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; + private readonly LibraryScanFailedDomainEventHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanFailedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockLibraryScanStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockLibraryScanStagingResultsRepository); + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockMediaLibrariesScanCancellationTracker = Substitute.For(); + _mockDebouncedLibraryScanProgressNotifier = Substitute.For(); + + // default stubs: the library scan update and the staging results clearing succeed + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new LibraryScanFailedDomainEventHandler(_mockDebouncedLibraryScanProgressNotifier, _mockMediaLibrariesScanCancellationTracker, _mockMediaLibrariesScanProgressTracker, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScanIsRunning_ShouldFailScanAndCleanupResources() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockLibraryScanRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(compositeId); + _mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(compositeId); + await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any()); + await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanIsNotRunning_ShouldSkipPersistenceButStillCleanupResources() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Failed); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(compositeId); + _mockMediaLibrariesScanProgressTracker.Received(1).RemoveScanProgress(compositeId); + await _mockLibraryScanStagingResultsRepository.Received(1).ClearForScanAsync(scan.Id, Arg.Any()); + await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFailedEventAsync(compositeId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to get library scan"); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); + await _mockLibraryScanStagingResultsRepository.DidNotReceive().ClearForScanAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + Error error = Error.Failure(description: "Failed to update library scan"); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenClearForScanFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFailedDomainEvent domainEvent = new(Guid.NewGuid(), _libraryIdFixture.Create(value: scan.LibraryId), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + Error error = Error.Failure(description: "Failed to clear staging results"); + _mockLibraryScanStagingResultsRepository.ClearForScanAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockDebouncedLibraryScanProgressNotifier.DidNotReceive().SendLibraryScanFailedEventAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs new file mode 100644 index 00000000..c73d7af9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanFinishedDomainEventHandlerTests.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFinishedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibrariesScanCancellationTracker _mockMediaLibrariesScanCancellationTracker; + private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; + private readonly LibraryScanFinishedDomainEventHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanFinishedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockMediaLibrariesScanCancellationTracker = Substitute.For(); + _mockDebouncedLibraryScanProgressNotifier = Substitute.For(); + + // default stubs: the library scan update succeeds + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new LibraryScanFinishedDomainEventHandler(_mockMediaLibrariesScanProgressTracker, _mockMediaLibrariesScanCancellationTracker, _mockDebouncedLibraryScanProgressNotifier, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScanIsRunning_ShouldFinishScanAndNotifyClients() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(Arg.Any(), compositeId).Returns(Result.Updated); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockLibraryScanRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockMediaLibrariesScanProgressTracker.Received(1).UpdateScanProgress(Arg.Any(), compositeId); + await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryScanFinishedEventAsync(compositeId, Arg.Any()); + _mockMediaLibrariesScanCancellationTracker.Received(1).RemoveScan(compositeId); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to get library scan"); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanIsNotRunning_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, exception.EventualConsistencyError); + await _mockLibraryScanRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create( + scanId: _scanIdFixture.Create(value: scan.Id), + userId: _userIdFixture.Create(value: scan.UserId)); + LibraryScanFinishedDomainEvent domainEvent = new(Guid.NewGuid(), compositeId, DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + Error error = Error.Failure(description: "Failed to update library scan"); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs new file mode 100644 index 00000000..2ae13b83 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanJobProgressChangedDomainEventHandlerTests.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanJobProgressChangedDomainEventHandlerTests +{ + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; + private readonly LibraryScanJobProgressChangedDomainEventHandler _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanJobProgressChangedDomainEventHandlerTests() + { + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockDebouncedLibraryScanProgressNotifier = Substitute.For(); + + _sut = new LibraryScanJobProgressChangedDomainEventHandler(_mockMediaLibrariesScanProgressTracker, _mockDebouncedLibraryScanProgressNotifier); + } + + [Fact] + public async Task HandleAsync_WhenScanJobProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 5, totalItems: 10, currentOperation: "Hashing"); + LibraryScanJobProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, progress, DateTime.UtcNow); + _mockMediaLibrariesScanProgressTracker.UpdateScanJobProgress(libraryId, compositeId, progress).Returns(Result.Updated); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockMediaLibrariesScanProgressTracker.Received(1).UpdateScanJobProgress(libraryId, compositeId, progress); + await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs new file mode 100644 index 00000000..a3d0bc71 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanProgressChangedDomainEventHandlerTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.Management.Events; +using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanProgressChangedDomainEventHandlerTests +{ + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IMediaLibraryScanProgressNotifier _mockDebouncedLibraryScanProgressNotifier; + private readonly LibraryScanProgressChangedDomainEventHandler _sut; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanProgressChangedDomainEventHandlerTests() + { + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockDebouncedLibraryScanProgressNotifier = Substitute.For(); + + _sut = new LibraryScanProgressChangedDomainEventHandler(_mockMediaLibrariesScanProgressTracker, _mockDebouncedLibraryScanProgressNotifier); + } + + [Fact] + public async Task HandleAsync_WhenScanProgressChanges_ShouldUpdateTrackerAndNotifySignalRClients() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + LibraryScanProgressChangedDomainEvent domainEvent = new(Guid.NewGuid(), libraryId, compositeId, DateTime.UtcNow); + _mockMediaLibrariesScanProgressTracker.UpdateScanProgress(libraryId, compositeId).Returns(Result.Updated); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + _mockMediaLibrariesScanProgressTracker.Received(1).UpdateScanProgress(libraryId, compositeId); + await _mockDebouncedLibraryScanProgressNotifier.Received(1).SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + } +} 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 new file mode 100644 index 00000000..8f4e33c7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandlerTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +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.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.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +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; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanQueuedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IMediaLibraryScanningService _mockMediaLibraryScanningService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly LibraryScanQueuedDomainEventHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanQueuedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockMediaLibraryScanningService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + + // default stubs: the scanning service starts the scan successfully + _mockMediaLibraryScanningService.StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); + + _sut = new LibraryScanQueuedDomainEventHandler(_mockMediaLibraryScanningService, _mockDomainEventsQueue, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScanExists_ShouldStartTheScan() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(scan.Id, Arg.Any()) + .Returns(Result.From(scan)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockMediaLibraryScanningService.Received(1).StartScanAsync( + Arg.Is(libraryScan => libraryScan.Id.Value == scan.Id), + scan.Library.LibraryType, + scan.Library.DownloadMetadataFromWeb, + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to get library scan"); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenScanDoesNotExist_ShouldThrowEventualConsistencyExceptionWithNotFoundError() + { + // Arrange + LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(), _libraryIdFixture.Create(), DateTime.UtcNow); + _mockLibraryScanRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Success(null)); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(DomainErrors.LibraryScanning.LibraryScanNotFound, exception.EventualConsistencyError); + await _mockMediaLibraryScanningService.DidNotReceive().StartScanAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenStartScanFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScanEntity scan = _libraryScanEntityFixture.Create(); + LibraryScanQueuedDomainEvent domainEvent = new(Guid.NewGuid(), _scanIdFixture.Create(value: scan.Id), _libraryIdFixture.Create(value: scan.LibraryId), DateTime.UtcNow); + _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()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs new file mode 100644 index 00000000..35944f59 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibraryScanStartedDomainEventHandlerTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.Management.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; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanStartedDomainEventHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly LibraryScanStartedDomainEventHandler _sut; + private readonly LibraryScanFixture _libraryScanFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanStartedDomainEventHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _sut = new LibraryScanStartedDomainEventHandler(_mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenScanStarts_ShouldUpdateScanStatusAndSaveChanges() + { + // Arrange + LibraryScan libraryScan = _libraryScanFixture.Create(); + LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + await _mockLibraryScanRepository.Received(1).UpdateAsync( + Arg.Is(scan => scan.Id == libraryScan.Id.Value), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldThrowEventualConsistencyException() + { + // Arrange + LibraryScan libraryScan = _libraryScanFixture.Create(); + LibraryScanStartedDomainEvent domainEvent = new(Guid.NewGuid(), libraryScan, DateTime.UtcNow); + Error error = Error.Failure(description: "Failed to update library scan"); + _mockLibraryScanRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + EventualConsistencyException exception = await Assert.ThrowsAsync( + () => _sut.HandleAsync(domainEvent, CancellationToken.None).AsTask()); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} 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 new file mode 100644 index 00000000..07363bed --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetEnabledLibraries/GetEnabledLibrariesQueryHandlerTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +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.Errors; +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.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 + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly GetEnabledLibrariesQueryHandler _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetEnabledLibrariesQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and is an admin + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _sut = new GetEnabledLibrariesQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnAllEnabledLibraries() + { + // Arrange + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: Guid.NewGuid()) + ]; + _mockLibraryRepository.GetAllEnabledAsync(Arg.Any()).Returns(Result.From>(libraries)); + + // Act + Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Length); + Assert.Equal(libraries[0].Id, result.Value[0].Id); + Assert.Equal(libraries[1].Id, result.Value[1].Id); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnOnlyLibrariesOwnedByTheUser() + { + // Arrange + Guid otherUserId = Guid.NewGuid(); + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: otherUserId) + ]; + _mockLibraryRepository.GetAllEnabledAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryResponse response = Assert.Single(result.Value); + Assert.Equal(libraries[0].Id, response.Id); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetAllEnabledAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllEnabledFails_ShouldReturnError() + { + // Arrange + _mockLibraryRepository.GetAllEnabledAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get enabled libraries")); + + // Act + Result result = await _sut.HandleAsync(new GetEnabledLibrariesQuery(), 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 new file mode 100644 index 00000000..622e3880 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraries/GetLibrariesQueryHandlerTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +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.Errors; +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.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 + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly GetLibrariesQueryHandler _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and is an admin + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + + _sut = new GetLibrariesQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnAllLibraries() + { + // Arrange + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: Guid.NewGuid()) + ]; + _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + + // Act + Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Length); + Assert.Equal(libraries[0].Id, result.Value[0].Id); + Assert.Equal(libraries[1].Id, result.Value[1].Id); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnOnlyLibrariesOwnedByTheUser() + { + // Arrange + Guid otherUserId = Guid.NewGuid(); + List libraries = + [ + _libraryEntityFixture.Create(userId: _userId), + _libraryEntityFixture.Create(userId: otherUserId) + ]; + _mockLibraryRepository.GetAllAsync(Arg.Any()).Returns(Result.From>(libraries)); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryResponse response = Assert.Single(result.Value); + Assert.Equal(libraries[0].Id, response.Id); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetAllFails_ShouldReturnError() + { + // Arrange + _mockLibraryRepository.GetAllAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get libraries")); + + // Act + Result result = await _sut.HandleAsync(new GetLibrariesQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs new file mode 100644 index 00000000..f9a061fc --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetLibraryScanProgress/GetLibraryScanProgressQueryHandlerTests.cs @@ -0,0 +1,201 @@ +#region ========================================================================= USING ===================================================================================== +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.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.Management.Queries.GetLibraryScanProgress; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.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.MediaLibrary; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly IValidator _mockValidator; + private readonly GetLibraryScanProgressQueryHandler _sut; + private readonly GetLibraryScanProgressQueryFixture _getLibraryScanProgressQueryFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryScanProgressQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated, the ownership policy allows access, and the scan has progress + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) + .Returns(Result.From(_mediaLibraryScanProgressFixture.Create( + userId: _userIdFixture.Create(value: _userId), + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running))); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetLibraryScanProgressQueryHandler(_mockMediaLibrariesScanProgressTracker, _mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnScanProgressResponse() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); + _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(1, result.Value.CompletedJobs); + Assert.Equal(2, result.Value.TotalJobs); + } + + [Fact] + public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError); + _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get library")); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); + _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + _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); + _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.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 _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGettingScanProgressFails_ShouldReturnError() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: query.LibraryId, userId: _userId); + _mockLibraryRepository.GetByIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From(library)); + _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get scan progress")); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying() + { + // Arrange + GetLibraryScanProgressQuery query = _getLibraryScanProgressQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Library.LibraryIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Library.LibraryIdCannotBeEmpty, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + _mockMediaLibrariesScanProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); + } +} 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 new file mode 100644 index 00000000..c5d3c2d8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Queries/GetRunningLibraryScans/GetRunningLibraryScansQueryHandlerTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +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.Errors; +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.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.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.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanRepository _mockLibraryScanRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IMediaLibrariesScanProgressTracker _mockMediaLibrariesScanProgressTracker; + private readonly GetRunningLibraryScansQueryHandler _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetRunningLibraryScansQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryScanRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanRepository.Returns(_mockLibraryScanRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockMediaLibrariesScanProgressTracker = Substitute.For(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated, is an admin, and every scan has progress + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); + _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) + .Returns(Result.From(_mediaLibraryScanProgressFixture.Create( + userId: _userIdFixture.Create(value: _userId), + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running))); + + _sut = new GetRunningLibraryScansQueryHandler(_mockMediaLibrariesScanProgressTracker, _mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenUserIsAdmin_ShouldReturnProgressForAllRunningScans() + { + // Arrange + List runningScans = + [ + _libraryScanEntityFixture.Create(userId: _userId), + _libraryScanEntityFixture.Create(userId: Guid.NewGuid()) + ]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + + // Act + Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAdmin_ShouldReturnProgressOnlyForScansOwnedByTheUser() + { + // Arrange + List runningScans = + [ + _libraryScanEntityFixture.Create(userId: _userId), + _libraryScanEntityFixture.Create(userId: Guid.NewGuid()) + ]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(false); + + // Act + Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError); + await _mockLibraryScanRepository.DidNotReceive().GetRunningScansAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetRunningScansFails_ShouldReturnError() + { + // Arrange + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get running scans")); + + // Act + Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task HandleAsync_WhenGettingScanProgressFails_ShouldReturnError() + { + // Arrange + List runningScans = [_libraryScanEntityFixture.Create(userId: _userId)]; + _mockLibraryScanRepository.GetRunningScansAsync(Arg.Any()).Returns(Result.From>(runningScans)); + _mockMediaLibrariesScanProgressTracker.GetScanProgress(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get scan progress")); + + // Act + Result> result = await _sut.HandleAsync(new GetRunningLibraryScansQuery(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } +} 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 8698100d..5d0e1272 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 @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -24,6 +25,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IValidator _mockValidator; private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; /// @@ -34,10 +36,10 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, mockValidator); + _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, _mockValidator); } [Fact] @@ -65,4 +67,22 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.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(new ReorderLibraryMetadataProvidersCommand(libraryId, [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()); + } } 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 85a16954..c0a5a097 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 @@ -4,6 +4,7 @@ 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.SetLibraryMetadataProviderEnabled; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -23,6 +24,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IValidator _mockValidator; private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; /// @@ -33,10 +35,10 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, mockValidator); + _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, _mockValidator); } [Fact] @@ -91,4 +93,23 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), 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(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, 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()); + } } 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 563a4584..7f172a0d 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,6 +3,7 @@ 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.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -22,6 +23,7 @@ public class UpdatePluginSettingsCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; + private readonly IValidator _mockValidator; private readonly UpdatePluginSettingsCommandHandler _sut; /// @@ -32,10 +34,10 @@ public class UpdatePluginSettingsCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); - IValidator mockValidator = Substitute.For>(); - mockValidator.Validate(Arg.Any()) + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) .Returns([]); - _sut = new UpdatePluginSettingsCommandHandler(_mockUnitOfWork, mockValidator); + _sut = new UpdatePluginSettingsCommandHandler(_mockUnitOfWork, _mockValidator); } [Fact] @@ -55,4 +57,22 @@ public class UpdatePluginSettingsCommandHandlerTests await _mockPluginRepository.Received(1).UpdateSettingsAsync(pluginId, Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + Dictionary settings = new() { ["preferredLanguage"] = "fr" }; + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); + await _mockPluginRepository.DidNotReceive().UpdateSettingsAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } } 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 new file mode 100644 index 00000000..774a02f9 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs @@ -0,0 +1,158 @@ +#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.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.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryMetadataProviderConfigurationRepository _mockLibraryMetadataProviderConfigurationRepository; + private readonly IPluginRepository _mockPluginRepository; + private readonly GetLibraryMetadataProvidersQueryHandler _sut; + private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryMetadataProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockLibraryMetadataProviderConfigurationRepository = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + + _sut = new GetLibraryMetadataProvidersQueryHandler(_mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnProvidersOrderedByRankWithPluginNames() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), + _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) + ]; + _mockLibraryMetadataProviderConfigurationRepository.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 + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + Guid unknownPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) + ]; + _mockLibraryMetadataProviderConfigurationRepository.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); + LibraryMetadataProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoConfigurationsExist_ShouldReturnEmptyList() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + _mockLibraryMetadataProviderConfigurationRepository.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 + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get configurations"); + _mockLibraryMetadataProviderConfigurationRepository.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 + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + _mockLibraryMetadataProviderConfigurationRepository.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); + } +} 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 new file mode 100644 index 00000000..00e7f486 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs @@ -0,0 +1,137 @@ +#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.Plugins; +using Lumina.Application.Common.Mapping.Plugins; +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 NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetPluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly IPluginManager _mockPluginManager; + private readonly GetPluginSettingsQueryHandler _sut; + private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockPluginManager = Substitute.For(); + + _sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsLoaded_ShouldReturnSchemaAndSettings() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); + _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + .Returns(Result.From(plugin)); + + 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"]) + ]); + _mockPluginManager.GetPlugin(query.PluginId).Returns(loadedPlugin); + IReadOnlyDictionary? expectedSettings = JsonSerializer.Deserialize>(plugin.SettingsJson!); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(query.PluginId, result.Value.PluginId); + Assert.Equal(2, result.Value.Schema.Count); + Assert.Equal("key1", result.Value.Schema[0].Key); + Assert.Equal(PluginSettingType.Text, result.Value.Schema[0].Type); + Assert.NotNull(result.Value.Settings); + Assert.Equal(expectedSettings, result.Value.Settings); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsNotLoaded_ShouldReturnEmptySchema() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + PluginEntity plugin = _pluginEntityFixture.Create(query.PluginId); + _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + .Returns(Result.From(plugin)); + _mockPluginManager.GetPlugin(query.PluginId).Returns((IPlugin?)null); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(query.PluginId, result.Value.PluginId); + Assert.Empty(result.Value.Schema); + } + + [Fact] + public async Task HandleAsync_WhenPluginDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginNotFound, result.FirstError); + _mockPluginManager.DidNotReceive().GetPlugin(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByIdFails_ShouldReturnError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get plugin"); + _mockPluginRepository.GetByIdAsync(query.PluginId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _mockPluginManager.DidNotReceive().GetPlugin(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs new file mode 100644 index 00000000..2c09dd77 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/PermissionDtoTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.DTO.Authentication; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PermissionDtoTests +{ + private readonly PermissionDtoFixture _permissionDtoFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingPermission_ShouldPreserveValues() + { + // Arrange + PermissionDto expected = _permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanViewUsers); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PermissionDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingPermission_ShouldSerializeEnumAsCamelCaseString() + { + // Arrange + PermissionDto sut = _permissionDtoFixture.Create(permissionName: AuthorizationPermission.CanDeleteUsers); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"PermissionName\":\"canDeleteUsers\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + PermissionDto first = _permissionDtoFixture.Create(id: id, permissionName: AuthorizationPermission.CanRegisterUsers); + PermissionDto second = _permissionDtoFixture.Create(id: id, permissionName: AuthorizationPermission.CanRegisterUsers); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs new file mode 100644 index 00000000..1a442586 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Authentication/RoleDtoTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Authentication; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RoleDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingRole_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + RoleDto expected = new(id, "Admin"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RoleDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + RoleDto first = new(id, "Admin"); + RoleDto second = new(id, "Admin"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs new file mode 100644 index 00000000..4b0fd356 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Filtering/LibraryFilterDtoTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common.Filtering; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common.Filtering; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryFilterDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void LibraryFilterDto_WhenConstructed_ShouldRequireLibraryId() + { + // Act + LibraryFilterDto sut = new() { LibraryId = Guid.NewGuid(), SearchTerm = "test" }; + + // Assert + Assert.NotEqual(Guid.Empty, sut.LibraryId); + } + + [Fact] + public void RoundTrip_WhenSerializingWithLibraryIdAndSearchTerm_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryFilterDto expected = new() { LibraryId = libraryId, SearchTerm = "fantasy" }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LibraryFilterDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected.LibraryId, actual.LibraryId); + Assert.Equal(expected.SearchTerm, actual.SearchTerm); + } + + [Fact] + public void RoundTrip_WhenDeserializingJsonWithoutLibraryId_ShouldThrowJsonException() + { + // Arrange + string json = """{ "searchTerm": "fantasy" }"""; + + // Act & Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, _jsonOptions)); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs new file mode 100644 index 00000000..bda11a0c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/GenreDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GenreDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGenre_ShouldPreserveName() + { + // Arrange + GenreDto expected = new("Science Fiction"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GenreDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + GenreDto first = new("Fantasy"); + GenreDto second = new("Fantasy"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs new file mode 100644 index 00000000..431b12e4 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/LanguageInfoDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingFullyPopulatedLanguageInfo_ShouldPreserveValues() + { + // Arrange + LanguageInfoDto expected = new("en", "English", "English"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LanguageInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + LanguageInfoDto first = new("fr", "French", "Français"); + LanguageInfoDto second = new("fr", "French", "Français"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs new file mode 100644 index 00000000..02e4fec9 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/Pagination/PaginationDataDtoTests.cs @@ -0,0 +1,117 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common.Pagination; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common.Pagination; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PaginationDataDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void CurrentPage_WhenNotSet_ShouldDefaultToOne() + { + // Arrange + PaginationDataDto sut = new(); + + // Act + int currentPage = sut.CurrentPage; + + // Assert + Assert.Equal(1, currentPage); + } + + [Fact] + public void PerPage_WhenNotSet_ShouldDefaultToTwoHundred() + { + // Arrange + PaginationDataDto sut = new(); + + // Act + int perPage = sut.PerPage; + + // Assert + Assert.Equal(200, perPage); + } + + [Theory] + [InlineData(0)] // zero is below the minimum + [InlineData(-5)] // negative values are below the minimum + public void CurrentPage_WhenSettingValueBelowOne_ShouldClampToOne(int value) + { + // Arrange + PaginationDataDto sut = new(); + + // Act + sut.CurrentPage = value; + + // Assert + Assert.Equal(1, sut.CurrentPage); + } + + [Theory] + [InlineData(0)] // zero is below the minimum + [InlineData(-10)] // negative values are below the minimum + public void PerPage_WhenSettingValueBelowOne_ShouldClampToOne(int value) + { + // Arrange + PaginationDataDto sut = new(); + + // Act + sut.PerPage = value; + + // Assert + Assert.Equal(1, sut.PerPage); + } + + [Fact] + public void CurrentPage_WhenSettingValueAboveOne_ShouldPreserveValue() + { + // Arrange + PaginationDataDto sut = new(); + + // Act + sut.CurrentPage = 5; + + // Assert + Assert.Equal(5, sut.CurrentPage); + } + + [Fact] + public void PerPage_WhenSettingValueAboveOne_ShouldPreserveValue() + { + // Arrange + PaginationDataDto sut = new(); + + // Act + sut.PerPage = 25; + + // Assert + Assert.Equal(25, sut.PerPage); + } + + [Fact] + public void RoundTrip_WhenSerializingValidPaginationData_ShouldPreserveValues() + { + // Arrange + PaginationDataDto expected = new() { CurrentPage = 3, PerPage = 50 }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PaginationDataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected.CurrentPage, actual.CurrentPage); + Assert.Equal(expected.PerPage, actual.PerPage); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs new file mode 100644 index 00000000..f1fc0b09 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/ReleaseInfoDtoTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingFullyPopulatedReleaseInfo_ShouldPreserveValues() + { + // Arrange + DateOnly originalReleaseDate = new(2005, 6, 15); + DateOnly reReleaseDate = new(2015, 9, 1); + ReleaseInfoDto expected = new( + originalReleaseDate, + 2005, + reReleaseDate, + 2015, + "US", + "Revised Edition" + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ReleaseInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingEmptyReleaseInfo_ShouldPreserveNullValues() + { + // Arrange + ReleaseInfoDto expected = new(null, null, null, null, null, null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ReleaseInfoDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + ReleaseInfoDto first = new(new DateOnly(2005, 6, 15), 2005, null, null, "US", null); + ReleaseInfoDto second = new(new DateOnly(2005, 6, 15), 2005, null, null, "US", null); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs new file mode 100644 index 00000000..c3302ff8 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/Common/TagDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.Common; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class TagDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingTag_ShouldPreserveName() + { + // Arrange + TagDto expected = new("bestseller"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + TagDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + TagDto first = new("award-winning"); + TagDto second = new("award-winning"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs new file mode 100644 index 00000000..b0a67d22 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/FileSystemManagement/FileSystemItemDtoTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.FileSystemManagement; +using Lumina.Contracts.Fixtures.Core.DTO.FileSystemManagement; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.FileSystemManagement; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemDtoTests +{ + private readonly FileSystemItemDtoFixture _fileSystemItemDtoFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidFileSystemItemDto() + { + // Act + FileSystemItemDto sut = _fileSystemItemDtoFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.False(string.IsNullOrWhiteSpace(sut.Name)); + } + + [Fact] + public void RoundTrip_WhenSerializingFileSystemItem_ShouldPreserveValues() + { + // Arrange + FileSystemItemDto expected = _fileSystemItemDtoFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + FileSystemItemDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + FileSystemItemDto first = _fileSystemItemDtoFixture.Create(); + FileSystemItemDto second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs new file mode 100644 index 00000000..03e7652c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorDtoTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingContributor_ShouldPreserveValues() + { + // Arrange + MediaContributorDto expected = new( + new MediaContributorNameDto("John Smith", "Johnathan Smith"), + new MediaContributorRoleDto("Author", "Writer") + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaContributorDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingContributorWithoutNameOrRole_ShouldPreserveNullValues() + { + // Arrange + MediaContributorDto expected = new(null, null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaContributorDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Name); + Assert.Null(actual.Role); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs new file mode 100644 index 00000000..c7321c39 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorNameDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingName_ShouldPreserveValues() + { + // Arrange + MediaContributorNameDto expected = new("John Smith", "Johnathan Smith"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaContributorNameDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + MediaContributorNameDto first = new("John Smith", null); + MediaContributorNameDto second = new("John Smith", null); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs new file mode 100644 index 00000000..a8a60fd4 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaContributors/MediaContributorRoleDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaContributors; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRoleDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingRole_ShouldPreserveValues() + { + // Arrange + MediaContributorRoleDto expected = new("Author", "Writer"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaContributorRoleDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + MediaContributorRoleDto first = new("Illustrator", null); + MediaContributorRoleDto second = new("Illustrator", null); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs new file mode 100644 index 00000000..44e2e36e --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/Management/LibraryContentLocationDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryContentLocationDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingContentLocation_ShouldPreservePath() + { + // Arrange + LibraryContentLocationDto expected = new(@"C:\Media\Books"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LibraryContentLocationDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + LibraryContentLocationDto first = new(@"/media/books"); + LibraryContentLocationDto second = new(@"/media/books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs new file mode 100644 index 00000000..3a159c46 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDtoTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +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; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookMetadataDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingFullyPopulatedMetadata_ShouldPreserveValues() + { + // Arrange + BookMetadataDto expected = new( + "Dune", + "Dune", + "A science fiction novel.", + new ReleaseInfoDto(new DateOnly(1965, 8, 1), 1965, null, null, "US", null), + [new GenreDto("Science Fiction")], + [new TagDto("classic")], + new LanguageInfoDto("en", "English", "English"), + null, + "Chilton Books", + 412, + BookFormat.Hardcover, + "First Edition", + 1, + new BookSeriesDto("Dune Chronicles"), + "B0006C7V9I", + "12345", + "68008446", + "ocm01234567", + "OL12345W", + "lccn123", + "abc123", + "1234567890", + "id12345", + [new IsbnDto("978-0-306-40615-7", IsbnFormat.Isbn13)], + [new MediaContributorDto(new MediaContributorNameDto("Frank Herbert", "Frank Herbert"), new MediaContributorRoleDto("Author", "Writer"))], + [new BookRatingDto(4.5m, 5m, BookRatingSource.Goodreads, 1000)], + "https://example.com/dune.jpg" + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingMetadata_ShouldSerializeFormatAsCamelCaseString() + { + // Arrange + BookMetadataDto sut = new( + "Dune", + null, + null, + null, + null, + null, + null, + null, + null, + null, + BookFormat.Paperback, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + ); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Format\":\"paperback\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs new file mode 100644 index 00000000..e09bd40c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataLookupDtoTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +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; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookMetadataLookupDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingLookupWithAllValues_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + BookMetadataLookupDto expected = new( + libraryId, + @"C:\Media\Books\dune.epub", + "978-0-306-40615-7", + "OL12345W", + "Dune", + "Frank Herbert", + "en" + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookMetadataLookupDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Constructor_WhenOmittingOptionalParameters_ShouldUseNullDefaults() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + BookMetadataLookupDto sut = new(libraryId, @"/media/books/dune.epub"); + + // Assert + Assert.Equal(libraryId, sut.LibraryId); + Assert.Equal(@"/media/books/dune.epub", sut.Path); + Assert.Null(sut.Isbn); + Assert.Null(sut.OpenLibraryId); + Assert.Null(sut.Title); + Assert.Null(sut.Author); + Assert.Null(sut.LanguageCode); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs new file mode 100644 index 00000000..477d40ea --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookRatingDtoTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookRatingDtoTests +{ + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidBookRatingDto() + { + // Act + BookRatingDto sut = _bookRatingDtoFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.True(sut.Value.HasValue); + Assert.True(sut.MaxValue.HasValue); + } + + [Fact] + public void Create_WhenOmittingOptionalProperties_ShouldReturnNullSourceAndVoteCount() + { + // Act + BookRatingDto sut = _bookRatingDtoFixture.Create(includeOptionalProperties: false); + + // Assert + Assert.Null(sut.Source); + Assert.Null(sut.VoteCount); + } + + [Fact] + public void RoundTrip_WhenSerializingRating_ShouldPreserveValues() + { + // Arrange + BookRatingDto expected = _bookRatingDtoFixture.Create(source: BookRatingSource.Goodreads); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookRatingDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingRating_ShouldSerializeSourceAsCamelCaseString() + { + // Arrange + BookRatingDto sut = _bookRatingDtoFixture.Create(source: BookRatingSource.OpenLibrary); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Source\":\"openLibrary\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + BookRatingDto first = _bookRatingDtoFixture.Create(value: 4, maxValue: 5, source: BookRatingSource.User, voteCount: 10); + BookRatingDto second = _bookRatingDtoFixture.Create(value: 4, maxValue: 5, source: BookRatingSource.User, voteCount: 10); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs new file mode 100644 index 00000000..045d7b67 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookSeriesDtoTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingSeries_ShouldPreserveTitle() + { + // Arrange + BookSeriesDto expected = new("The Wheel of Time"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookSeriesDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + BookSeriesDto first = new("Dune"); + BookSeriesDto second = new("Dune"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs new file mode 100644 index 00000000..b47a13ec --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/IsbnDtoTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class IsbnDtoTests +{ + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidIsbnDto() + { + // Act + IsbnDto sut = _isbnDtoFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Value)); + } + + [Fact] + public void Create_WhenFormatIsIsbn10_ShouldReturnIsbn10Value() + { + // Act + IsbnDto sut = _isbnDtoFixture.Create(format: IsbnFormat.Isbn10); + + // Assert + Assert.Equal(IsbnFormat.Isbn10, sut.Format); + Assert.Contains("-", sut.Value, StringComparison.Ordinal); + } + + [Fact] + public void RoundTrip_WhenSerializingIsbn_ShouldPreserveValues() + { + // Arrange + IsbnDto expected = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + IsbnDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingIsbn_ShouldSerializeFormatAsCamelCaseString() + { + // Arrange + IsbnDto sut = _isbnDtoFixture.Create(format: IsbnFormat.Isbn13); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Format\":\"isbn13\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + IsbnDto first = _isbnDtoFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); + IsbnDto second = _isbnDtoFixture.Create(value: "978-0-306-40615-7", format: IsbnFormat.Isbn13); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs new file mode 100644 index 00000000..34d3ac26 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/DTO/MediaLibrary/WrittenContentLibrary/WrittenContentMetadataDtoTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.DTO.MediaLibrary.WrittenContentLibrary; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataDtoTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingFullyPopulatedMetadata_ShouldPreserveValues() + { + // Arrange + WrittenContentMetadataDto expected = new( + "Dune", + "Dune", + "A science fiction novel.", + new ReleaseInfoDto(new DateOnly(1965, 8, 1), 1965, null, null, "US", null), + [new GenreDto("Science Fiction")], + [new TagDto("classic")], + new LanguageInfoDto("en", "English", "English"), + null, + "Chilton Books", + 412 + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + WrittenContentMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingMetadataWithoutOptionalValues_ShouldPreserveNullValues() + { + // Arrange + WrittenContentMetadataDto expected = new( + "Title", + null, + null, + null, + null, + null, + null, + null, + null, + null + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + WrittenContentMetadataDto? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj b/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj new file mode 100644 index 00000000..090657ac --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Lumina.Contracts.UnitTests.csproj @@ -0,0 +1,40 @@ + + + + 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.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs new file mode 100644 index 00000000..f3beab59 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/ChangePasswordRequestTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordRequestTests +{ + private readonly ChangePasswordRequestFixture _changePasswordRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidChangePasswordRequest() + { + // Act + ChangePasswordRequest sut = _changePasswordRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Username)); + Assert.False(string.IsNullOrWhiteSpace(sut.CurrentPassword)); + Assert.False(string.IsNullOrWhiteSpace(sut.NewPassword)); + Assert.Equal(sut.NewPassword, sut.NewPasswordConfirm); + } + + [Fact] + public void RoundTrip_WhenSerializingChangePasswordRequest_ShouldPreserveValues() + { + // Arrange + ChangePasswordRequest expected = _changePasswordRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ChangePasswordRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + ChangePasswordRequest sut = _changePasswordRequestFixture.Create(); + + // Act + (string? username, string? currentPassword, string? newPassword, string? newPasswordConfirm) = sut; + + // Assert + Assert.Equal(sut.Username, username); + Assert.Equal(sut.CurrentPassword, currentPassword); + Assert.Equal(sut.NewPassword, newPassword); + Assert.Equal(sut.NewPasswordConfirm, newPasswordConfirm); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs new file mode 100644 index 00000000..2117e376 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/LoginRequestTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginRequestTests +{ + private readonly LoginRequestFixture _loginRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidLoginRequest() + { + // Act + LoginRequest sut = _loginRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Username)); + Assert.False(string.IsNullOrWhiteSpace(sut.Password)); + } + + [Fact] + public void RoundTrip_WhenSerializingLoginRequest_ShouldPreserveValues() + { + // Arrange + LoginRequest expected = _loginRequestFixture.Create(totpCode: "123456"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LoginRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + LoginRequest first = new("user1", "pass1", null); + LoginRequest second = new("user1", "pass1", null); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + LoginRequest sut = _loginRequestFixture.Create(username: "user1", password: "pass1", totpCode: "123456"); + + // Act + (string? username, string? password, string? totpCode) = sut; + + // Assert + Assert.Equal(sut.Username, username); + Assert.Equal(sut.Password, password); + Assert.Equal(sut.TotpCode, totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs new file mode 100644 index 00000000..f0c3d8af --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RecoverPasswordRequestTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordRequestTests +{ + private readonly RecoverPasswordRequestFixture _recoverPasswordRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidRecoverPasswordRequest() + { + // Act + RecoverPasswordRequest sut = _recoverPasswordRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Username)); + Assert.False(string.IsNullOrWhiteSpace(sut.TotpCode)); + } + + [Fact] + public void RoundTrip_WhenSerializingRecoverPasswordRequest_ShouldPreserveValues() + { + // Arrange + RecoverPasswordRequest expected = _recoverPasswordRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RecoverPasswordRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + RecoverPasswordRequest sut = _recoverPasswordRequestFixture.Create(username: "user1", totpCode: "123456"); + + // Act + (string? username, string? totpCode) = sut; + + // Assert + Assert.Equal(sut.Username, username); + Assert.Equal(sut.TotpCode, totpCode); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs new file mode 100644 index 00000000..df2ed957 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authentication/RegistrationRequestTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Requests.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationRequestTests +{ + private readonly RegistrationRequestFixture _registrationRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidRegistrationRequest() + { + // Act + RegistrationRequest sut = _registrationRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Username)); + Assert.False(string.IsNullOrWhiteSpace(sut.Password)); + Assert.Equal(sut.Password, sut.PasswordConfirm); + } + + [Fact] + public void Constructor_WhenOmittingUse2fa_ShouldDefaultToTrue() + { + // Act + RegistrationRequest sut = new(Username: "user1", Password: "pass1", PasswordConfirm: "pass1"); + + // Assert + Assert.True(sut.Use2fa); + } + + [Fact] + public void RoundTrip_WhenSerializingRegistrationRequest_ShouldPreserveValues() + { + // Arrange + RegistrationRequest expected = _registrationRequestFixture.Create(use2fa: true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RegistrationRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + RegistrationRequest sut = _registrationRequestFixture.Create(username: "user1", password: "pass1", passwordConfirm: "pass1", use2fa: false); + + // Act + (string? username, string? password, string? passwordConfirm, bool use2fa) = sut; + + // Assert + Assert.Equal(sut.Username, username); + Assert.Equal(sut.Password, password); + Assert.Equal(sut.PasswordConfirm, passwordConfirm); + Assert.Equal(sut.Use2fa, use2fa); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs new file mode 100644 index 00000000..62cc785d --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/AddRoleRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class AddRoleRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingAddRoleRequest_ShouldPreserveValues() + { + // Arrange + List permissions = [Guid.NewGuid(), Guid.NewGuid()]; + AddRoleRequest expected = new("Admin", permissions); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + AddRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingAddRoleRequestWithNullPermissions_ShouldPreserveNull() + { + // Arrange + AddRoleRequest expected = new("Admin", null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + AddRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Permissions); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs new file mode 100644 index 00000000..8cfb7864 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/DeleteRoleRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteRoleRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingDeleteRoleRequest_ShouldPreserveValues() + { + // Arrange + Guid roleId = Guid.NewGuid(); + DeleteRoleRequest expected = new(roleId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + DeleteRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingDeleteRoleRequestWithNullRoleId_ShouldPreserveNull() + { + // Arrange + DeleteRoleRequest expected = new(null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + DeleteRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.RoleId); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs new file mode 100644 index 00000000..45d11c62 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetAuthorizationRequestTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Requests.Authorization; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetAuthorizationRequestTests +{ + private readonly GetAuthorizationRequestFixture _getAuthorizationRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetAuthorizationRequest() + { + // Act + GetAuthorizationRequest sut = _getAuthorizationRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.True(sut.UserId.HasValue); + } + + [Fact] + public void Constructor_WhenPassingNullUserId_ShouldReturnNullUserId() + { + // Act + GetAuthorizationRequest sut = new(UserId: null); + + // Assert + Assert.Null(sut.UserId); + } + + [Fact] + public void RoundTrip_WhenSerializingGetAuthorizationRequest_ShouldPreserveValues() + { + // Arrange + GetAuthorizationRequest expected = _getAuthorizationRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetAuthorizationRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs new file mode 100644 index 00000000..ff84c382 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetRolePermissionsRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetRolePermissionsRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetRolePermissionsRequest_ShouldPreserveValues() + { + // Arrange + Guid roleId = Guid.NewGuid(); + GetRolePermissionsRequest expected = new(roleId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetRolePermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid roleId = Guid.NewGuid(); + GetRolePermissionsRequest first = new(roleId); + GetRolePermissionsRequest second = new(roleId); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs new file mode 100644 index 00000000..16931359 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserPermissionsRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserPermissionsRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetUserPermissionsRequest_ShouldPreserveValues() + { + // Arrange + Guid userId = Guid.NewGuid(); + GetUserPermissionsRequest expected = new(userId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetUserPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingGetUserPermissionsRequestWithNullUserId_ShouldPreserveNull() + { + // Arrange + GetUserPermissionsRequest expected = new(null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetUserPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.UserId); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs new file mode 100644 index 00000000..5c2747f9 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/GetUserRoleRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetUserRoleRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetUserRoleRequest_ShouldPreserveValues() + { + // Arrange + Guid userId = Guid.NewGuid(); + GetUserRoleRequest expected = new(userId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetUserRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingGetUserRoleRequestWithNullUserId_ShouldPreserveNull() + { + // Arrange + GetUserRoleRequest expected = new(null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetUserRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.UserId); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs new file mode 100644 index 00000000..dceaa6ed --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateRoleRequestTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Requests.Authorization; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateRoleRequestTests +{ + private readonly UpdateRoleRequestFixture _updateRoleRequestFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdateRoleRequest_ShouldPreserveValues() + { + // Arrange + UpdateRoleRequest expected = _updateRoleRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingUpdateRoleRequestWithNullPermissions_ShouldPreserveNull() + { + // Arrange + UpdateRoleRequest expected = _updateRoleRequestFixture.Create() with { Permissions = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateRoleRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Permissions); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs new file mode 100644 index 00000000..15d0d8f9 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Authorization/UpdateUserRoleAndPermissionsRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Authorization; +using Lumina.Contracts.Requests.Authorization; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserRoleAndPermissionsRequestTests +{ + private readonly UpdateUserRoleAndPermissionsRequestFixture _updateUserRoleAndPermissionsRequestFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdateUserRoleAndPermissionsRequest_ShouldPreserveValues() + { + // Arrange + UpdateUserRoleAndPermissionsRequest expected = _updateUserRoleAndPermissionsRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateUserRoleAndPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingWithOptionalValuesOmitted_ShouldPreserveNulls() + { + // Arrange + UpdateUserRoleAndPermissionsRequest expected = _updateUserRoleAndPermissionsRequestFixture.Create() with { RoleId = null, Permissions = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateUserRoleAndPermissionsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.RoleId); + Assert.Null(actual.Permissions); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs new file mode 100644 index 00000000..5e2c5cf8 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Directories/GetDirectoriesRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Directories; +using Lumina.Contracts.Requests.FileSystemManagement.Directories; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetDirectoriesRequestTests +{ + private readonly GetDirectoriesRequestFixture _getDirectoriesRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetDirectoriesRequest() + { + // Act + GetDirectoriesRequest sut = _getDirectoriesRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingGetDirectoriesRequest_ShouldPreserveValues() + { + // Arrange + GetDirectoriesRequest expected = _getDirectoriesRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetDirectoriesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetDirectoriesRequest sut = _getDirectoriesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: true); + + // Act + (string? path, bool includeHiddenElements) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs new file mode 100644 index 00000000..1c47e9d6 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetFilesRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Files; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetFilesRequestTests +{ + private readonly GetFilesRequestFixture _getFilesRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetFilesRequest() + { + // Act + GetFilesRequest sut = _getFilesRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingGetFilesRequest_ShouldPreserveValues() + { + // Arrange + GetFilesRequest expected = _getFilesRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetFilesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetFilesRequest sut = _getFilesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: true); + + // Act + (string? path, bool includeHiddenElements) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs new file mode 100644 index 00000000..cf41d6c8 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Files/GetTreeFilesRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Files; +using Lumina.Contracts.Requests.FileSystemManagement.Files; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Files; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetTreeFilesRequestTests +{ + private readonly GetTreeFilesRequestFixture _getTreeFilesRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetTreeFilesRequest() + { + // Act + GetTreeFilesRequest sut = _getTreeFilesRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingGetTreeFilesRequest_ShouldPreserveValues() + { + // Arrange + GetTreeFilesRequest expected = _getTreeFilesRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetTreeFilesRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetTreeFilesRequest sut = _getTreeFilesRequestFixture.Create(path: @"C:\Media", includeHiddenElements: false); + + // Act + (string? path, bool includeHiddenElements) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs new file mode 100644 index 00000000..d452f298 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CheckPathExistsRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class CheckPathExistsRequestTests +{ + private readonly CheckPathExistsRequestFixture _checkPathExistsRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidCheckPathExistsRequest() + { + // Act + CheckPathExistsRequest sut = _checkPathExistsRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingCheckPathExistsRequest_ShouldPreserveValues() + { + // Arrange + CheckPathExistsRequest expected = _checkPathExistsRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + CheckPathExistsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + CheckPathExistsRequest sut = _checkPathExistsRequestFixture.Create(path: @"C:\Media\Books", includeHiddenElements: true); + + // Act + (string? path, bool includeHiddenElements) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.IncludeHiddenElements, includeHiddenElements); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs new file mode 100644 index 00000000..9f610065 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/CombinePathRequestTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class CombinePathRequestTests +{ + private readonly CombinePathRequestFixture _combinePathRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidCombinePathRequest() + { + // Act + CombinePathRequest sut = _combinePathRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.OriginalPath)); + Assert.False(string.IsNullOrWhiteSpace(sut.NewPath)); + } + + [Fact] + public void RoundTrip_WhenSerializingCombinePathRequest_ShouldPreserveValues() + { + // Arrange + CombinePathRequest expected = _combinePathRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + CombinePathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + CombinePathRequest sut = _combinePathRequestFixture.Create(originalPath: @"C:\Media", newPath: "books"); + + // Act + (string? originalPath, string? newPath) = sut; + + // Assert + Assert.Equal(sut.OriginalPath, originalPath); + Assert.Equal(sut.NewPath, newPath); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs new file mode 100644 index 00000000..c76597db --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathParentRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPathParentRequestTests +{ + private readonly GetPathParentRequestFixture _getPathParentRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetPathParentRequest() + { + // Act + GetPathParentRequest sut = _getPathParentRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingGetPathParentRequest_ShouldPreserveValues() + { + // Arrange + GetPathParentRequest expected = _getPathParentRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetPathParentRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + GetPathParentRequest first = _getPathParentRequestFixture.Create(path: @"C:\Media\Books"); + GetPathParentRequest second = _getPathParentRequestFixture.Create(path: @"C:\Media\Books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs new file mode 100644 index 00000000..7fe7263e --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/GetPathRootRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPathRootRequestTests +{ + private readonly GetPathRootRequestFixture _getPathRootRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetPathRootRequest() + { + // Act + GetPathRootRequest sut = _getPathRootRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingGetPathRootRequest_ShouldPreserveValues() + { + // Arrange + GetPathRootRequest expected = _getPathRootRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetPathRootRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + GetPathRootRequest first = _getPathRootRequestFixture.Create(path: @"C:\Media\Books"); + GetPathRootRequest second = _getPathRootRequestFixture.Create(path: @"C:\Media\Books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs new file mode 100644 index 00000000..7383f6a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/SplitPathRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class SplitPathRequestTests +{ + private readonly SplitPathRequestFixture _splitPathRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidSplitPathRequest() + { + // Act + SplitPathRequest sut = _splitPathRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingSplitPathRequest_ShouldPreserveValues() + { + // Arrange + SplitPathRequest expected = _splitPathRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + SplitPathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + SplitPathRequest first = _splitPathRequestFixture.Create(path: @"C:\Media\Books"); + SplitPathRequest second = _splitPathRequestFixture.Create(path: @"C:\Media\Books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs new file mode 100644 index 00000000..9c38e380 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Path/ValidatePathRequestTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Path; +using Lumina.Contracts.Requests.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ValidatePathRequestTests +{ + private readonly ValidatePathRequestFixture _validatePathRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidValidatePathRequest() + { + // Act + ValidatePathRequest sut = _validatePathRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingValidatePathRequest_ShouldPreserveValues() + { + // Arrange + ValidatePathRequest expected = _validatePathRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ValidatePathRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + ValidatePathRequest first = _validatePathRequestFixture.Create(path: @"C:\Media\Books"); + ValidatePathRequest second = _validatePathRequestFixture.Create(path: @"C:\Media\Books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs new file mode 100644 index 00000000..accf4387 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/FileSystemManagement/Thumbnails/GetThumbnailRequestTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.FileSystemManagement.Thumbnails; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetThumbnailRequestTests +{ + private readonly GetThumbnailRequestFixture _getThumbnailRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetThumbnailRequest() + { + // Act + GetThumbnailRequest sut = _getThumbnailRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.InRange(sut.Quality, 1, 100); + } + + [Fact] + public void RoundTrip_WhenSerializingGetThumbnailRequest_ShouldPreserveValues() + { + // Arrange + GetThumbnailRequest expected = _getThumbnailRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetThumbnailRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetThumbnailRequest sut = _getThumbnailRequestFixture.Create(path: @"C:\Media\cover.jpg", quality: 80); + + // Act + (string? path, int quality) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.Quality, quality); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs new file mode 100644 index 00000000..69278ec0 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs @@ -0,0 +1,74 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues() + { + // Arrange + AddLibraryRequest expected = new( + "Books", + "Book", + [@"C:\Media\Books"], + null, + true, + false, + true, + false, + true + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + AddLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + AddLibraryRequest sut = new( + "Books", + "Book", + [@"C:\Media\Books"], + null, + true, + false, + true, + false, + true + ); + + // Act + (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + + // Assert + Assert.Equal(sut.Title, title); + Assert.Equal(sut.LibraryType, libraryType); + Assert.Equal(sut.ContentLocations, contentLocations); + Assert.Equal(sut.CoverImage, coverImage); + Assert.Equal(sut.IsEnabled, isEnabled); + Assert.Equal(sut.IsLocked, isLocked); + Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); + Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs new file mode 100644 index 00000000..f3eec36c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/CancelLibraryScanRequestTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingCancelLibraryScanRequest_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + CancelLibraryScanRequest expected = new(libraryId, scanId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + CancelLibraryScanRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + CancelLibraryScanRequest first = new(libraryId, scanId); + CancelLibraryScanRequest second = new(libraryId, scanId); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs new file mode 100644 index 00000000..543241ed --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/DeleteLibraryRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingDeleteLibraryRequest_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + DeleteLibraryRequest expected = new(id); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + DeleteLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + DeleteLibraryRequest first = new(id); + DeleteLibraryRequest second = new(id); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs new file mode 100644 index 00000000..c2c10d95 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetLibraryRequest_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + GetLibraryRequest expected = new(id); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + GetLibraryRequest first = new(id); + GetLibraryRequest second = new(id); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs new file mode 100644 index 00000000..56e9d13a --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/GetLibraryScanProgressRequestTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetLibraryScanProgressRequest_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + GetLibraryScanProgressRequest expected = new(libraryId, scanId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetLibraryScanProgressRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid scanId = Guid.NewGuid(); + GetLibraryScanProgressRequest first = new(libraryId, scanId); + GetLibraryScanProgressRequest second = new(libraryId, scanId); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs new file mode 100644 index 00000000..8fe86c31 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/ScanLibraryRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingScanLibraryRequest_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + ScanLibraryRequest expected = new(id); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ScanLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + ScanLibraryRequest first = new(id); + ScanLibraryRequest second = new(id); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs new file mode 100644 index 00000000..ae55cab5 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdateLibraryRequest_ShouldPreserveValues() + { + // 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 + ); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateLibraryRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // 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 + ); + + // Act + (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + + // Assert + Assert.Equal(sut.Id, sutId); + Assert.Equal(sut.UserId, sutUserId); + Assert.Equal(sut.Title, title); + Assert.Equal(sut.LibraryType, libraryType); + Assert.Equal(sut.ContentLocations, contentLocations); + Assert.Equal(sut.CoverImage, coverImage); + Assert.Equal(sut.IsEnabled, isEnabled); + Assert.Equal(sut.IsLocked, isLocked); + Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); + Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); + } +} 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 new file mode 100644 index 00000000..63854886 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequestTests.cs @@ -0,0 +1,124 @@ +#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.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +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.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class AddBookRequestTests +{ + private readonly AddBookRequestFixture _addBookRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidAddBookRequest() + { + // Act + AddBookRequest sut = _addBookRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.NotEqual(Guid.Empty, sut.LibraryId); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.NotNull(sut.Metadata); + Assert.NotNull(sut.ISBNs); + Assert.NotEmpty(sut.ISBNs); + Assert.NotNull(sut.Contributors); + Assert.NotEmpty(sut.Contributors); + Assert.NotNull(sut.Ratings); + Assert.NotEmpty(sut.Ratings); + } + + [Fact] + public void RoundTrip_WhenSerializingAddBookRequest_ShouldPreserveValues() + { + // Arrange + AddBookRequest expected = _addBookRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + AddBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingAddBookRequest_ShouldSerializeFormatAsCamelCaseString() + { + // Arrange + AddBookRequest sut = _addBookRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Format\":\"", json, StringComparison.Ordinal); + Assert.DoesNotContain("\"Format\":\"0\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + 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; + + // Assert + Assert.Equal(sut.LibraryId, libraryId); + Assert.Equal(sut.Path, path); + Assert.Equal(sut.Metadata, metadata); + Assert.Equal(sut.Format, format); + Assert.Equal(sut.Edition, edition); + Assert.Equal(sut.VolumeNumber, volumeNumber); + Assert.Equal(sut.Series, series); + Assert.Equal(sut.ASIN, asin); + Assert.Equal(sut.GoodreadsId, goodreadsId); + Assert.Equal(sut.LCCN, lccn); + Assert.Equal(sut.OCLCNumber, oclcNumber); + Assert.Equal(sut.OpenLibraryId, openLibraryId); + Assert.Equal(sut.LibraryThingId, libraryThingId); + Assert.Equal(sut.GoogleBooksId, googleBooksId); + Assert.Equal(sut.BarnesAndNobleId, barnesAndNobleId); + Assert.Equal(sut.AppleBooksId, appleBooksId); + Assert.Equal(sut.ISBNs, isbns); + Assert.Equal(sut.Contributors, contributors); + Assert.Equal(sut.Ratings, ratings); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + AddBookRequest first = _addBookRequestFixture.Create(); + AddBookRequest second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs new file mode 100644 index 00000000..670e6dd9 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBookRequestTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBookRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetBookRequest_ShouldPreserveValues() + { + // Arrange + GetBookRequest expected = new("bookId-123"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingGetBookRequestWithNullId_ShouldPreserveNull() + { + // Arrange + GetBookRequest expected = new(null); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetBookRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Id); + } +} 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 new file mode 100644 index 00000000..bb8829ec --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBooksLiteRequestTests +{ + private readonly GetBooksLiteRequestFixture _getBooksLiteRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetBooksLiteRequest() + { + // Act + GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.NotEqual(Guid.Empty, sut.LibraryId); + Assert.True(sut.CurrentPage.HasValue); + Assert.True(sut.PerPage.HasValue); + } + + [Fact] + public void RoundTrip_WhenSerializingGetBooksLiteRequest_ShouldPreserveValues() + { + // Arrange + GetBooksLiteRequest expected = _getBooksLiteRequestFixture.Create(sortOrder: SortOrder.Descending); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetBooksLiteRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingGetBooksLiteRequest_ShouldSerializeSortOrderAsCamelCaseString() + { + // Arrange + GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(sortOrder: SortOrder.Ascending); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"SortOrder\":\"ascending\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetBooksLiteRequest sut = _getBooksLiteRequestFixture.Create(); + + // Act + (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker, string? sortBy, SortOrder? sortOrder) = sut; + + // Assert + Assert.Equal(sut.LibraryId, libraryId); + Assert.Equal(sut.CurrentPage, currentPage); + Assert.Equal(sut.PerPage, perPage); + Assert.Equal(sut.SearchTerm, searchTerm); + Assert.Equal(sut.FilterAlphaKey, filterAlphaKey); + Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.SortBy, sortBy); + Assert.Equal(sut.SortOrder, sortOrder); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs new file mode 100644 index 00000000..1b573070 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksRequestTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetBooksRequestTests +{ + private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidGetBooksRequest() + { + // Act + GetBooksRequest sut = _getBooksRequestFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.NotEqual(Guid.Empty, sut.LibraryId); + Assert.True(sut.CurrentPage.HasValue); + Assert.True(sut.PerPage.HasValue); + } + + [Fact] + public void RoundTrip_WhenSerializingGetBooksRequest_ShouldPreserveValues() + { + // Arrange + GetBooksRequest expected = _getBooksRequestFixture.Create(sortOrder: SortOrder.Ascending); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetBooksRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingGetBooksRequest_ShouldSerializeSortOrderAsCamelCaseString() + { + // Arrange + GetBooksRequest sut = _getBooksRequestFixture.Create(sortOrder: SortOrder.Descending); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"SortOrder\":\"descending\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + GetBooksRequest sut = _getBooksRequestFixture.Create(); + + // Act + (Guid libraryId, int? currentPage, int? perPage, string? searchTerm, string? sortBy, SortOrder? sortOrder) = sut; + + // Assert + Assert.Equal(sut.LibraryId, libraryId); + Assert.Equal(sut.CurrentPage, currentPage); + Assert.Equal(sut.PerPage, perPage); + Assert.Equal(sut.SearchTerm, searchTerm); + Assert.Equal(sut.SortBy, sortBy); + Assert.Equal(sut.SortOrder, sortOrder); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs new file mode 100644 index 00000000..eb3ea59b --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetLibraryMetadataProvidersRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetLibraryMetadataProvidersRequest_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetLibraryMetadataProvidersRequest expected = new(libraryId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + GetLibraryMetadataProvidersRequest first = new(libraryId); + GetLibraryMetadataProvidersRequest second = new(libraryId); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs new file mode 100644 index 00000000..c2bc4944 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/GetPluginSettingsRequestTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingGetPluginSettingsRequest_ShouldPreserveValues() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + GetPluginSettingsRequest expected = new(pluginId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + GetPluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + GetPluginSettingsRequest first = new(pluginId); + GetPluginSettingsRequest second = new(pluginId); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs new file mode 100644 index 00000000..41334634 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/ReorderLibraryMetadataProvidersRequestTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingReorderLibraryMetadataProvidersRequest_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List pluginIds = [Guid.NewGuid(), Guid.NewGuid()]; + ReorderLibraryMetadataProvidersRequest expected = new(libraryId, pluginIds); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ReorderLibraryMetadataProvidersRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + List pluginIds = [Guid.NewGuid()]; + ReorderLibraryMetadataProvidersRequest sut = new(libraryId, pluginIds); + + // Act + (Guid sutLibraryId, IReadOnlyList sutPluginIds) = sut; + + // Assert + Assert.Equal(sut.LibraryId, sutLibraryId); + Assert.Equal(sut.PluginIds, sutPluginIds); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs new file mode 100644 index 00000000..2eea3255 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingSetLibraryMetadataProviderEnabledRequest_ShouldPreserveValues() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + SetLibraryMetadataProviderEnabledRequest expected = new(libraryId, pluginId, true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + SetLibraryMetadataProviderEnabledRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + SetLibraryMetadataProviderEnabledRequest sut = new(libraryId, pluginId, false); + + // Act + (Guid sutLibraryId, Guid sutPluginId, bool isEnabled) = sut; + + // Assert + Assert.Equal(sut.LibraryId, sutLibraryId); + Assert.Equal(sut.PluginId, sutPluginId); + Assert.Equal(sut.IsEnabled, isEnabled); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs new file mode 100644 index 00000000..a4c2b14b --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/Plugins/UpdatePluginSettingsRequestTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsRequestTests +{ + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdatePluginSettingsRequest_ShouldPreserveValues() + { + // Arrange + UpdatePluginSettingsRequest expected = _updatePluginSettingsRequestFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdatePluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingUpdatePluginSettingsRequestWithNullSettings_ShouldPreserveNull() + { + // Arrange + UpdatePluginSettingsRequest expected = _updatePluginSettingsRequestFixture.Create() with { Settings = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdatePluginSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Settings); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs new file mode 100644 index 00000000..44bfcd8b --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsRequestTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues() + { + // Arrange + UpdateUserSettingsRequest expected = new(true, 50, true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UpdateUserSettingsRequest? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + UpdateUserSettingsRequest sut = new(false, 25, false); + + // Act + (bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker) = sut; + + // Assert + Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); + Assert.Equal(sut.ItemsPerPage, itemsPerPage); + Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs new file mode 100644 index 00000000..0b943997 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/ChangePasswordResponseTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ChangePasswordResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingChangePasswordResponse_ShouldPreserveValues() + { + // Arrange + ChangePasswordResponse expected = new(true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ChangePasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingFalseChangePasswordResponse_ShouldPreserveFalse() + { + // Arrange + ChangePasswordResponse expected = new(false); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ChangePasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.False(actual.IsPasswordChanged); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + ChangePasswordResponse first = new(true); + ChangePasswordResponse second = new(true); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs new file mode 100644 index 00000000..8b0830a3 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/LoginResponseTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Authentication; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LoginResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingLoginResponse_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + LoginResponse expected = new(id, "testUser", "jwt_token", true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LoginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + LoginResponse first = new(id, "testUser", "jwt_token", false); + LoginResponse second = new(id, "testUser", "jwt_token", false); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LoginResponse sut = new(id, "testUser", "jwt_token", true); + + // Act + (Guid sutId, string username, string token, bool usesTotp) = sut; + + // Assert + Assert.Equal(sut.Id, sutId); + Assert.Equal(sut.Username, username); + Assert.Equal(sut.Token, token); + Assert.Equal(sut.UsesTotp, usesTotp); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs new file mode 100644 index 00000000..f178b627 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RecoverPasswordResponseTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Authentication; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RecoverPasswordResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingRecoverPasswordResponse_ShouldPreserveValues() + { + // Arrange + RecoverPasswordResponse expected = new(true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RecoverPasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingFalseRecoverPasswordResponse_ShouldPreserveFalse() + { + // Arrange + RecoverPasswordResponse expected = new(false); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RecoverPasswordResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.False(actual.IsPasswordReset); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + RecoverPasswordResponse first = new(true); + RecoverPasswordResponse second = new(true); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs new file mode 100644 index 00000000..8e5b740c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authentication/RegistrationResponseTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Authentication; +using Lumina.Contracts.Responses.Authentication; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authentication; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RegistrationResponseTests +{ + private readonly RegistrationResponseFixture _registrationResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingRegistrationResponse_ShouldPreserveValues() + { + // Arrange + RegistrationResponse expected = _registrationResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RegistrationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingRegistrationResponseWithNullTotpSecret_ShouldPreserveNull() + { + // Arrange + RegistrationResponse expected = _registrationResponseFixture.Create() with { TotpSecret = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RegistrationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.TotpSecret); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + RegistrationResponse sut = _registrationResponseFixture.Create(); + + // Act + (Guid sutId, string username, string? totpSecret) = sut; + + // Assert + Assert.Equal(sut.Id, sutId); + Assert.Equal(sut.Username, username); + Assert.Equal(sut.TotpSecret, totpSecret); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs new file mode 100644 index 00000000..0ca9ec15 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/AuthorizationResponseTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +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; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Serialize_WhenSerializingAuthorizationResponse_ShouldPreserveValues() + { + // Arrange + Guid userId = Guid.NewGuid(); + HashSet permissions = [AuthorizationPermission.CanViewUsers, AuthorizationPermission.CanDeleteUsers]; + AuthorizationResponse expected = new(userId, "Admin", permissions); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + + // Assert + Assert.Contains($"\"UserId\":\"{userId}\"", json, StringComparison.Ordinal); + Assert.Contains("\"Role\":\"Admin\"", json, StringComparison.Ordinal); + Assert.Contains("canViewUsers", json, StringComparison.Ordinal); + Assert.Contains("canDeleteUsers", json, StringComparison.Ordinal); + } + + [Fact] + public void Serialize_WhenSerializingAuthorizationResponse_ShouldSerializePermissionsAsCamelCaseStrings() + { + // Arrange + Guid userId = Guid.NewGuid(); + HashSet permissions = [AuthorizationPermission.CanRegisterUsers]; + AuthorizationResponse sut = new(userId, "Admin", permissions); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("canRegisterUsers", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid userId = Guid.NewGuid(); + HashSet permissions = [AuthorizationPermission.None]; + AuthorizationResponse sut = new(userId, null, permissions); + + // Act + (Guid sutUserId, string? role, IReadOnlySet sutPermissions) = sut; + + // Assert + Assert.Equal(sut.UserId, sutUserId); + Assert.Equal(sut.Role, role); + Assert.Equal(sut.Permissions, sutPermissions); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs new file mode 100644 index 00000000..db6d35ff --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/PermissionResponseTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PermissionResponseTests +{ + private readonly PermissionResponseFixture _permissionResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingPermissionResponse_ShouldPreserveValues() + { + // Arrange + PermissionResponse expected = _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanCreateLibraries); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PermissionResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingPermissionResponse_ShouldSerializePermissionNameAsCamelCaseString() + { + // Arrange + PermissionResponse sut = _permissionResponseFixture.Create(permissionName: AuthorizationPermission.CanCreateLibraries); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"PermissionName\":\"canCreateLibraries\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs new file mode 100644 index 00000000..dd940302 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RolePermissionsResponseTests.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Authentication; +using Lumina.Contracts.Fixtures.Core.Responses.Authorization; +using Lumina.Contracts.Responses.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RolePermissionsResponseTests +{ + private readonly RolePermissionsResponseFixture _rolePermissionsResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingRolePermissionsResponse_ShouldPreserveValues() + { + // Arrange + RolePermissionsResponse expected = _rolePermissionsResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RolePermissionsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingRolePermissionsResponse_ShouldSerializePermissionNameAsCamelCaseString() + { + // Arrange + RolePermissionsResponse sut = _rolePermissionsResponseFixture.Create(permissions: + [ + new PermissionDto(Guid.NewGuid(), AuthorizationPermission.CanDeleteUsers) + ]); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("canDeleteUsers", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs new file mode 100644 index 00000000..a1a2a27d --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Authorization/RoleResponseTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Authorization; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class RoleResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingRoleResponse_ShouldPreserveValues() + { + // Arrange + Guid id = Guid.NewGuid(); + RoleResponse expected = new(id, "Admin"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + RoleResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + Guid id = Guid.NewGuid(); + RoleResponse first = new(id, "Admin"); + RoleResponse second = new(id, "Admin"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs new file mode 100644 index 00000000..c4899b3a --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Common/PaginatedResponseTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Common; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PaginatedResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void PaginatedResponse_WhenConstructed_ShouldRequireAllProperties() + { + // Act + PaginatedResponse sut = new() + { + Data = [1, 2, 3], + CurrentPage = 1, + PerPage = 10, + Count = 3, + NumberOfPages = 1 + }; + + // Assert + Assert.Equal([1, 2, 3], sut.Data); + Assert.Equal(1, sut.CurrentPage); + Assert.Equal(10, sut.PerPage); + Assert.Equal(3, sut.Count); + Assert.Equal(1, sut.NumberOfPages); + } + + [Fact] + public void RoundTrip_WhenSerializingPaginatedResponse_ShouldPreserveValues() + { + // Arrange + PaginatedResponse expected = new() + { + Data = ["book1", "book2"], + CurrentPage = 2, + PerPage = 20, + Count = 2, + NumberOfPages = 1 + }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PaginatedResponse? actual = JsonSerializer.Deserialize>(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected.Data, actual.Data); + Assert.Equal(expected.CurrentPage, actual.CurrentPage); + Assert.Equal(expected.PerPage, actual.PerPage); + Assert.Equal(expected.Count, actual.Count); + Assert.Equal(expected.NumberOfPages, actual.NumberOfPages); + } + + [Fact] + public void Deserialize_WhenDataIsMissing_ShouldThrowJsonException() + { + // Arrange + string json = """{ "currentPage": 1, "perPage": 10, "count": 0, "numberOfPages": 0 }"""; + + // Act & Assert + Assert.Throws(() => JsonSerializer.Deserialize>(json, _jsonOptions)); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + PaginatedResponse first = new() + { + Data = [1, 2, 3], + CurrentPage = 1, + PerPage = 10, + Count = 3, + NumberOfPages = 1 + }; + PaginatedResponse second = first with { }; + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs new file mode 100644 index 00000000..c581247f --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Common/FileSystemTreeNodeResponseTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Common; +using Lumina.Contracts.Responses.FileSystemManagement.Common; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTreeNodeResponseTests +{ + private readonly FileSystemTreeNodeResponseFixture _fileSystemTreeNodeResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Constructor_WhenInstantiatingNode_ShouldInitializeEmptyChildren() + { + // Act + FileSystemTreeNodeResponse sut = new(); + + // Assert + Assert.NotNull(sut.Children); + Assert.Empty(sut.Children); + } + + [Fact] + public void Create_WhenCalled_ShouldReturnValidTreeNode() + { + // Act + FileSystemTreeNodeResponse sut = _fileSystemTreeNodeResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.False(string.IsNullOrWhiteSpace(sut.Name)); + Assert.Equal(FileSystemItemType.Directory, sut.ItemType); + } + + [Fact] + public void RoundTrip_WhenSerializingTreeNode_ShouldPreserveValues() + { + // Arrange + FileSystemTreeNodeResponse expected = _fileSystemTreeNodeResponseFixture.Create(maxDepth: 1, maxChildren: 2); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + FileSystemTreeNodeResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected.Path, actual.Path); + Assert.Equal(expected.Name, actual.Name); + Assert.Equal(expected.ItemType, actual.ItemType); + Assert.Equal(expected.Children.Count, actual.Children.Count); + } + + [Fact] + public void Serialize_WhenSerializingTreeNode_ShouldSerializeItemTypeAsCamelCaseString() + { + // Arrange + FileSystemTreeNodeResponse sut = new() + { + Path = @"C:\Media", + Name = "Media", + ItemType = FileSystemItemType.Directory, + IsExpanded = false, + ChildrenLoaded = true, + Children = [] + }; + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"ItemType\":\"directory\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs new file mode 100644 index 00000000..de3182c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Directories/DirectoryResponseTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Directories; +using Lumina.Contracts.Responses.FileSystemManagement.Directories; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Directories; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class DirectoryResponseTests +{ + private readonly DirectoryResponseFixture _directoryResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidDirectoryResponse() + { + // Act + DirectoryResponse sut = _directoryResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.False(string.IsNullOrWhiteSpace(sut.Name)); + Assert.NotEmpty(sut.Items); + } + + [Fact] + public void RoundTrip_WhenSerializingDirectoryResponse_ShouldPreserveValues() + { + // Arrange + DirectoryResponse expected = _directoryResponseFixture.Create(itemCount: 2); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + DirectoryResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + DirectoryResponse sut = _directoryResponseFixture.Create(itemCount: 1); + + // Act + (string path, string name, System.DateTime dateCreated, System.DateTime dateModified, System.Collections.Generic.List items) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.Name, name); + Assert.Equal(sut.DateCreated, dateCreated); + Assert.Equal(sut.DateModified, dateModified); + Assert.Equal(sut.Items, items); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs new file mode 100644 index 00000000..be33dfd6 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/FileSystem/FileSystemTypeResponseTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.FileSystem; +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.FileSystem; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class FileSystemTypeResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingFileSystemTypeResponse_ShouldPreserveValues() + { + // Arrange + FileSystemTypeResponse expected = new(PlatformType.Windows); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + FileSystemTypeResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingFileSystemTypeResponse_ShouldSerializePlatformTypeAsCamelCaseString() + { + // Arrange + FileSystemTypeResponse sut = new(PlatformType.Unix); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"PlatformType\":\"unix\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + FileSystemTypeResponse first = new(PlatformType.Windows); + FileSystemTypeResponse second = new(PlatformType.Windows); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs new file mode 100644 index 00000000..6e2630b4 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Files/FileResponseTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Files; +using Lumina.Contracts.Responses.FileSystemManagement.Files; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Files; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class FileResponseTests +{ + private readonly FileResponseFixture _fileResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidFileResponse() + { + // Act + FileResponse sut = _fileResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + Assert.False(string.IsNullOrWhiteSpace(sut.Name)); + } + + [Fact] + public void RoundTrip_WhenSerializingFileResponse_ShouldPreserveValues() + { + // Arrange + FileResponse expected = _fileResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + FileResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + FileResponse sut = _fileResponseFixture.Create(); + + // Act + (string path, string name, System.DateTime dateCreated, System.DateTime dateModified, long size) = sut; + + // Assert + Assert.Equal(sut.Path, path); + Assert.Equal(sut.Name, name); + Assert.Equal(sut.DateCreated, dateCreated); + Assert.Equal(sut.DateModified, dateModified); + Assert.Equal(sut.Size, size); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs new file mode 100644 index 00000000..ed857e8f --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathExistsResponseTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PathExistsResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingPathExistsResponse_ShouldPreserveValues() + { + // Arrange + PathExistsResponse expected = new(true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PathExistsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + PathExistsResponse first = new(true); + PathExistsResponse second = new(true); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs new file mode 100644 index 00000000..de0fcfe7 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSegmentResponseTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PathSegmentResponseTests +{ + private readonly PathSegmentResponseFixture _pathSegmentResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidPathSegmentResponse() + { + // Act + PathSegmentResponse sut = _pathSegmentResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Path)); + } + + [Fact] + public void RoundTrip_WhenSerializingPathSegmentResponse_ShouldPreserveValues() + { + // Arrange + PathSegmentResponse expected = _pathSegmentResponseFixture.Create(path: @"C:\Media"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PathSegmentResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + PathSegmentResponse first = _pathSegmentResponseFixture.Create(path: @"C:\Media\Books"); + PathSegmentResponse second = _pathSegmentResponseFixture.Create(path: @"C:\Media\Books"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs new file mode 100644 index 00000000..ad35c768 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathSeparatorResponseTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Path; +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PathSeparatorResponseTests +{ + private readonly PathSeparatorResponseFixture _pathSeparatorResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidPathSeparatorResponse() + { + // Act + PathSeparatorResponse sut = _pathSeparatorResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.False(string.IsNullOrWhiteSpace(sut.Separator)); + } + + [Fact] + public void RoundTrip_WhenSerializingPathSeparatorResponse_ShouldPreserveValues() + { + // Arrange + PathSeparatorResponse expected = _pathSeparatorResponseFixture.Create(separator: "\\"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PathSeparatorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + PathSeparatorResponse first = _pathSeparatorResponseFixture.Create(separator: "/"); + PathSeparatorResponse second = _pathSeparatorResponseFixture.Create(separator: "/"); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs new file mode 100644 index 00000000..8c887c9e --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Path/PathValidResponseTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.FileSystemManagement.Path; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Path; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PathValidResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingPathValidResponse_ShouldPreserveValues() + { + // Arrange + PathValidResponse expected = new(true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PathValidResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + PathValidResponse first = new(true); + PathValidResponse second = new(true); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs new file mode 100644 index 00000000..c385fb4e --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/FileSystemManagement/Thumbnails/ThumbnailResponseTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.FileSystemManagement.Thumbnails; +using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.FileSystemManagement.Thumbnails; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class ThumbnailResponseTests +{ + private readonly ThumbnailResponseFixture _thumbnailResponseFixture = new(); + + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void Create_WhenCalled_ShouldReturnValidThumbnailResponse() + { + // Act + ThumbnailResponse sut = _thumbnailResponseFixture.Create(); + + // Assert + Assert.NotNull(sut); + Assert.NotEmpty(sut.Bytes); + } + + [Fact] + public void RoundTrip_WhenSerializingThumbnailResponse_ShouldPreserveValues() + { + // Arrange + ThumbnailResponse expected = _thumbnailResponseFixture.Create(type: ImageType.JPEG); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + ThumbnailResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected.Type, actual.Type); + Assert.Equal(expected.Bytes, actual.Bytes); + } + + [Fact] + public void Serialize_WhenSerializingThumbnailResponse_ShouldSerializeTypeAsCamelCaseString() + { + // Arrange + ThumbnailResponse sut = _thumbnailResponseFixture.Create(type: ImageType.PNG); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Type\":\"png\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs new file mode 100644 index 00000000..601c64db --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryResponseTests +{ + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingLibraryResponse_ShouldPreserveValues() + { + // Arrange + LibraryResponse expected = _libraryResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LibraryResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingLibraryResponse_ShouldSerializeLibraryTypeAsCamelCaseString() + { + // Arrange + LibraryResponse sut = _libraryResponseFixture.Create(libraryType: LibraryType.Movie); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"LibraryType\":\"movie\"", json, StringComparison.Ordinal); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + 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; + + // Assert + Assert.Equal(sut.Id, id); + Assert.Equal(sut.UserId, userId); + Assert.Equal(sut.Title, title); + Assert.Equal(sut.LibraryType, libraryType); + Assert.Equal(sut.ContentLocations, contentLocations); + Assert.Equal(sut.CoverImage, coverImage); + Assert.Equal(sut.IsEnabled, isEnabled); + Assert.Equal(sut.IsLocked, isLocked); + Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); + Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); + Assert.Equal(sut.CreatedOnUtc, createdOnUtc); + Assert.Equal(sut.UpdatedOnUtc, updatedOnUtc); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs new file mode 100644 index 00000000..f58bf1e2 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanJobProgressResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProgressResponseTests +{ + private readonly MediaLibraryScanJobProgressResponseFixture _mediaLibraryScanJobProgressResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingMediaLibraryScanJobProgressResponse_ShouldPreserveValues() + { + // Arrange + MediaLibraryScanJobProgressResponse expected = _mediaLibraryScanJobProgressResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaLibraryScanJobProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + MediaLibraryScanJobProgressResponse sut = _mediaLibraryScanJobProgressResponseFixture.Create(); + + // Act + (int completedItems, int totalItems, string currentOperation, decimal progressPercentage) = sut; + + // Assert + Assert.Equal(sut.CompletedItems, completedItems); + Assert.Equal(sut.TotalItems, totalItems); + Assert.Equal(sut.CurrentOperation, currentOperation); + Assert.Equal(sut.ProgressPercentage, progressPercentage); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs new file mode 100644 index 00000000..5f10977c --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanProgressResponseTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProgressResponseTests +{ + private readonly MediaLibraryScanProgressResponseFixture _mediaLibraryScanProgressResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingMediaLibraryScanProgressResponse_ShouldPreserveValues() + { + // Arrange + MediaLibraryScanProgressResponse expected = _mediaLibraryScanProgressResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaLibraryScanProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingWithoutCurrentJobProgress_ShouldPreserveNull() + { + // Arrange + MediaLibraryScanProgressResponse expected = _mediaLibraryScanProgressResponseFixture.Create() with { CurrentJobProgress = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaLibraryScanProgressResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.CurrentJobProgress); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + MediaLibraryScanProgressResponse sut = _mediaLibraryScanProgressResponseFixture.Create(); + + // Act + (Guid scanId, Guid userId, Guid libraryId, int totalJobs, int completedJobs, MediaLibraryScanJobProgressResponse? currentJobProgress, string status, decimal overallProgressPercentage) = sut; + + // Assert + Assert.Equal(sut.ScanId, scanId); + Assert.Equal(sut.UserId, userId); + Assert.Equal(sut.LibraryId, libraryId); + Assert.Equal(sut.TotalJobs, totalJobs); + Assert.Equal(sut.CompletedJobs, completedJobs); + Assert.Equal(sut.CurrentJobProgress, currentJobProgress); + Assert.Equal(sut.Status, status); + Assert.Equal(sut.OverallProgressPercentage, overallProgressPercentage); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs new file mode 100644 index 00000000..e7e9a048 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/MediaLibraryScanResponseTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.Management; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingMediaLibraryScanResponse_ShouldPreserveValues() + { + // Arrange + Guid scanId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + MediaLibraryScanResponse expected = new(scanId, libraryId); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + MediaLibraryScanResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid scanId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + MediaLibraryScanResponse sut = new(scanId, libraryId); + + // Act + (Guid sutScanId, Guid sutLibraryId) = sut; + + // Assert + Assert.Equal(sut.ScanId, sutScanId); + Assert.Equal(sut.LibraryId, sutLibraryId); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs new file mode 100644 index 00000000..2b8b51bc --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookLiteResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookLiteResponseTests +{ + private readonly BookLiteResponseFixture _bookLiteResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingBookLiteResponse_ShouldPreserveValues() + { + // Arrange + BookLiteResponse expected = _bookLiteResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookLiteResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingBookLiteResponseWithNullValues_ShouldPreserveNulls() + { + // Arrange + BookLiteResponse expected = _bookLiteResponseFixture.Create() with { ReleaseYear = null, CoverPath = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookLiteResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.ReleaseYear); + Assert.Null(actual.CoverPath); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + BookLiteResponse sut = _bookLiteResponseFixture.Create(); + + // Act + (Guid sutId, string title, int? releaseYear, string? coverPath) = sut; + + // Assert + Assert.Equal(sut.Id, sutId); + Assert.Equal(sut.Title, title); + Assert.Equal(sut.ReleaseYear, releaseYear); + Assert.Equal(sut.CoverPath, coverPath); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs new file mode 100644 index 00000000..3bc196c4 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponseTests.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class BookResponseTests +{ + private readonly BookResponseFixture _bookResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingBookResponse_ShouldPreserveValues() + { + // Arrange + BookResponse expected = _bookResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + BookResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void Serialize_WhenSerializingBookResponse_ShouldSerializeEnumsAsCamelCaseStrings() + { + // Arrange + BookResponse sut = _bookResponseFixture.Create( + format: BookFormat.Paperback, + metadataStatus: MetadataStatus.Pending); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Format\":\"paperback\"", json, StringComparison.Ordinal); + Assert.Contains("\"MetadataStatus\":\"pending\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs new file mode 100644 index 00000000..f0f2c8dd --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/LibraryMetadataProviderResponseTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingProviderResponse_ShouldPreserveValues() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderResponse expected = new(pluginId, "OpenLibrary", true, 1); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + LibraryMetadataProviderResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderResponse sut = new(pluginId, "OpenLibrary", false, 2); + + // Act + (Guid sutPluginId, string name, bool isEnabled, int rank) = sut; + + // Assert + Assert.Equal(sut.PluginId, sutPluginId); + Assert.Equal(sut.Name, name); + Assert.Equal(sut.IsEnabled, isEnabled); + Assert.Equal(sut.Rank, rank); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs new file mode 100644 index 00000000..23e94eff --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PluginResponseTests +{ + private readonly PluginResponseFixture _pluginResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingPluginResponse_ShouldPreserveValues() + { + // Arrange + PluginResponse expected = _pluginResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingFailedPluginResponse_ShouldPreserveLoadError() + { + // Arrange + PluginResponse expected = _pluginResponseFixture.Create( + loadStatus: PluginLoadStatus.FailedToLoad, + loadError: "Missing dependency"); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(PluginLoadStatus.FailedToLoad, actual.LoadStatus); + Assert.Equal("Missing dependency", actual.LoadError); + } + + [Fact] + public void Serialize_WhenSerializingPluginResponse_ShouldSerializeLoadStatusAsCamelCaseString() + { + // Arrange + PluginResponse sut = _pluginResponseFixture.Create(loadStatus: PluginLoadStatus.Loaded); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"LoadStatus\":\"loaded\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs new file mode 100644 index 00000000..66022abf --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingDescriptorResponseTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingDescriptorResponseTests +{ + private readonly PluginSettingDescriptorResponseFixture _pluginSettingDescriptorResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void RoundTrip_WhenSerializingDescriptor_ShouldPreserveValues() + { + // Arrange + PluginSettingDescriptorResponse expected = _pluginSettingDescriptorResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginSettingDescriptorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingDescriptorWithoutOptionalValues_ShouldPreserveNulls() + { + // Arrange + PluginSettingDescriptorResponse expected = _pluginSettingDescriptorResponseFixture.Create() with { DefaultValue = null, AllowedValues = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginSettingDescriptorResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.DefaultValue); + Assert.Null(actual.AllowedValues); + } + + [Fact] + public void Serialize_WhenSerializingDescriptor_ShouldSerializeTypeAsCamelCaseString() + { + // Arrange + PluginSettingDescriptorResponse sut = _pluginSettingDescriptorResponseFixture.Create(type: PluginSettingType.Number); + + // Act + string json = JsonSerializer.Serialize(sut, _jsonOptions); + + // Assert + Assert.Contains("\"Type\":\"number\"", json, StringComparison.Ordinal); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs new file mode 100644 index 00000000..fb8075b8 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/Plugins/PluginSettingsResponseTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.Plugins; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingsResponseTests +{ + private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingPluginSettingsResponse_ShouldPreserveValues() + { + // Arrange + PluginSettingsResponse expected = _pluginSettingsResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + // Assert + Assert.NotNull(actual); + Assert.Equivalent(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingPluginSettingsResponseWithNullSettings_ShouldPreserveNull() + { + // Arrange + PluginSettingsResponse expected = _pluginSettingsResponseFixture.Create() with { Settings = null }; + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + PluginSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Null(actual.Settings); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs new file mode 100644 index 00000000..fa2a5569 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/InitializationResponseTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.UsersManagement; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.UsersManagement; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class InitializationResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingInitializationResponse_ShouldPreserveValues() + { + // Arrange + InitializationResponse expected = new(true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + InitializationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingFalseInitializationResponse_ShouldPreserveFalse() + { + // Arrange + InitializationResponse expected = new(false); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + InitializationResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.False(actual.IsInitialized); + } + + [Fact] + public void Equality_WhenTwoInstancesHaveSameValues_ShouldBeEqual() + { + // Arrange + InitializationResponse first = new(true); + InitializationResponse second = new(true); + + // Act + bool areEqual = first == second; + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs new file mode 100644 index 00000000..ac566276 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsResponseTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUserSettingsResponse_ShouldPreserveValues() + { + // Arrange + Guid userId = Guid.NewGuid(); + UserSettingsResponse expected = new(userId, true, 50, true); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UserSettingsResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + Guid userId = Guid.NewGuid(); + UserSettingsResponse sut = new(userId, false, 25, false); + + // Act + (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker) = sut; + + // Assert + Assert.Equal(sut.UserId, sutUserId); + Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); + Assert.Equal(sut.ItemsPerPage, itemsPerPage); + Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + } +} diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs new file mode 100644 index 00000000..1e8c9894 --- /dev/null +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Users/UserResponseTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Users; +using Lumina.Contracts.Responses.UsersManagement.Users; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Users; + +/// +/// Contains unit tests for the record. +/// +[ExcludeFromCodeCoverage] +public class UserResponseTests +{ + private readonly UserResponseFixture _userResponseFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + [Fact] + public void RoundTrip_WhenSerializingUserResponse_ShouldPreserveValues() + { + // Arrange + UserResponse expected = _userResponseFixture.Create(); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UserResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(expected, actual); + } + + [Fact] + public void RoundTrip_WhenSerializingUserResponseWithUpdatedOnUtc_ShouldPreserveValue() + { + // Arrange + DateTime updatedOnUtc = DateTime.UtcNow.AddDays(1); + UserResponse expected = _userResponseFixture.Create(updatedOnUtc: updatedOnUtc); + + // Act + string json = JsonSerializer.Serialize(expected, _jsonOptions); + UserResponse? actual = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.NotNull(actual); + Assert.Equal(updatedOnUtc, actual.UpdatedOnUtc); + } + + [Fact] + public void Deconstruct_WhenCalled_ShouldReturnAllProperties() + { + // Arrange + UserResponse sut = _userResponseFixture.Create(); + + // Act + (Guid sutId, string username, DateTime sutCreatedOnUtc, DateTime? sutUpdatedOnUtc) = sut; + + // Assert + Assert.Equal(sut.Id, sutId); + Assert.Equal(sut.Username, username); + Assert.Equal(sut.CreatedOnUtc, sutCreatedOnUtc); + Assert.Equal(sut.UpdatedOnUtc, sutUpdatedOnUtc); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs new file mode 100644 index 00000000..9b6a2766 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/BookConfigurationTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public BookConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Books", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + IProperty titleProperty = entityType.GetProperty(nameof(BookEntity.Title)); + IProperty pathProperty = entityType.GetProperty(nameof(BookEntity.Path)); + IProperty formatProperty = entityType.GetProperty(nameof(BookEntity.Format)); + IProperty metadataStatusProperty = entityType.GetProperty(nameof(BookEntity.MetadataStatus)); + + // Assert + Assert.False(titleProperty.IsNullable); + Assert.Equal(255, titleProperty.GetMaxLength()); + Assert.False(pathProperty.IsNullable); + Assert.Equal(2048, pathProperty.GetMaxLength()); + Assert.Equal(typeof(BookFormat?), formatProperty.ClrType); + Assert.Equal("TEXT", formatProperty.GetColumnType()); + Assert.Equal(typeof(MetadataStatus), metadataStatusProperty.ClrType); + Assert.Equal("TEXT", metadataStatusProperty.GetColumnType()); + Assert.Equal(20, metadataStatusProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedTypesForRatingsAndIsbns() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + List ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)]; + + // Assert + Assert.Equal(2, ownedTypes.Count); + Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(BookRatingEntity) && ownedType.GetTableName() == "BookRatings"); + Assert.Contains(ownedTypes, ownedType => ownedType.ClrType == typeof(IsbnEntity) && ownedType.GetTableName() == "BookISBNs"); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureManyToManyJoinTablesForTagsAndGenres() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + List skipNavigations = [.. entityType.GetSkipNavigations()]; + + // Assert + Assert.Equal(2, skipNavigations.Count); + Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Tags) && navigation.JoinEntityType.GetTableName() == "BookTags"); + Assert.Contains(skipNavigations, navigation => navigation.Name == nameof(BookEntity.Genres) && navigation.JoinEntityType.GetTableName() == "BookGenres"); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexesOnLibraryIdAndPath() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.Path)])); + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(BookEntity.LibraryId), nameof(BookEntity.MetadataStatus)])); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(BookEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(BookEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(BookEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/DirectoryScanFingerprintConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/DirectoryScanFingerprintConfigurationTests.cs new file mode 100644 index 00000000..65c2a167 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/DirectoryScanFingerprintConfigurationTests.cs @@ -0,0 +1,88 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DirectoryScanFingerprintConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public DirectoryScanFingerprintConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("DirectoryScanFingerprints", tableName); + Assert.Equal([nameof(DirectoryScanFingerprintEntity.LibraryId), nameof(DirectoryScanFingerprintEntity.Path)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!; + + // Act + IProperty pathProperty = entityType.GetProperty(nameof(DirectoryScanFingerprintEntity.Path)); + IProperty lastWriteTimeUtcProperty = entityType.GetProperty(nameof(DirectoryScanFingerprintEntity.LastWriteTimeUtc)); + + // Assert + Assert.False(pathProperty.IsNullable); + Assert.Equal(1024, pathProperty.GetMaxLength()); + Assert.False(lastWriteTimeUtcProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!; + + // Act + IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(LibraryEntity), foreignKey.PrincipalEntityType.ClrType); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + Assert.Equal(nameof(DirectoryScanFingerprintEntity.LibraryId), foreignKey.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(DirectoryScanFingerprintEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes()); + + // Assert + Assert.Equal(nameof(DirectoryScanFingerprintEntity.LibraryId), index.Properties[0].Name); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/GenreConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/GenreConfigurationTests.cs new file mode 100644 index 00000000..91e72af8 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/GenreConfigurationTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GenreConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public GenreConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(GenreEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Genres", tableName); + Assert.Equal([nameof(GenreEntity.Name)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureNameAsRequired() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(GenreEntity))!; + + // Act + IProperty nameProperty = entityType.GetProperty(nameof(GenreEntity.Name)); + + // Assert + Assert.False(nameProperty.IsNullable); + Assert.Equal(50, nameProperty.GetMaxLength()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs new file mode 100644 index 00000000..0cade107 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -0,0 +1,114 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Libraries", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + 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)); + + // Assert + Assert.False(titleProperty.IsNullable); + Assert.Equal(255, titleProperty.GetMaxLength()); + Assert.Equal(typeof(LibraryType), libraryTypeProperty.ClrType); + Assert.Equal("TEXT", libraryTypeProperty.GetColumnType()); + Assert.Equal(true, isEnabledProperty.GetDefaultValue()); + Assert.Equal(true, downloadMetadataProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOwnedContentLocations() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + List ownedTypes = [.. _context.Model.GetEntityTypes().Where(ownedType => ownedType.IsOwned() && ownedType.FindOwnership()?.PrincipalEntityType.Name == entityType.Name)]; + + // Assert + IEntityType contentLocationType = Assert.Single(ownedTypes); + Assert.Equal(typeof(LibraryContentLocationEntity), contentLocationType.ClrType); + Assert.Equal("LibraryContentLocations", contentLocationType.GetTableName()); + Assert.Equal(260, contentLocationType.GetProperty(nameof(LibraryContentLocationEntity.Path)).GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationships() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys()); + List navigations = [.. entityType.GetNavigations()]; + + // Assert + Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior); + Assert.Equal(nameof(LibraryEntity.UserId), userForeignKey.Properties[0].Name); + Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.User)); + Assert.Contains(navigations, navigation => navigation.Name == nameof(LibraryEntity.LibraryScans) && navigation.IsCollection); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryMetadataProviderConfigurationConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryMetadataProviderConfigurationConfigurationTests.cs new file mode 100644 index 00000000..b587a457 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryMetadataProviderConfigurationConfigurationTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderConfigurationConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryMetadataProviderConfigurationConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("LibraryMetadataProviderConfigurations", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!; + + // Act + IProperty libraryIdProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.LibraryId)); + IProperty pluginIdProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.PluginId)); + IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.IsEnabled)); + IProperty rankProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.Rank)); + + // Assert + Assert.False(libraryIdProperty.IsNullable); + Assert.False(pluginIdProperty.IsNullable); + Assert.False(isEnabledProperty.IsNullable); + Assert.False(rankProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryIdAndPluginId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes()); + + // Assert + Assert.Equal([nameof(LibraryMetadataProviderConfigurationEntity.LibraryId), nameof(LibraryMetadataProviderConfigurationEntity.PluginId)], index.Properties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryMetadataProviderConfigurationEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryMetadataProviderConfigurationEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanConfigurationTests.cs new file mode 100644 index 00000000..4ec8f45e --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanConfigurationTests.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("LibraryScans", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureStatusAsRequiredString() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!; + + // Act + IProperty statusProperty = entityType.GetProperty(nameof(LibraryScanEntity.Status)); + + // Assert + Assert.False(statusProperty.IsNullable); + Assert.Equal(typeof(LibraryScanJobStatus), statusProperty.ClrType); + Assert.Equal("TEXT", statusProperty.GetColumnType()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipsWithUserAndLibrary() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + Assert.Equal(2, foreignKeys.Count); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(LibraryEntity) && foreignKey.Properties[0].Name == nameof(LibraryScanEntity.LibraryId)); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.Properties[0].Name == nameof(LibraryScanEntity.UserId)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureDescendingIndexOnLibraryIdStatusAndCreatedOnUtc() + { + // Arrange + // the read-optimized runtime model does not store the index sort order, so the design-time model is inspected instead + IDesignTimeModel designTimeModel = _context.GetService(); + IEntityType entityType = designTimeModel.Model.FindEntityType(typeof(LibraryScanEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanEntity.LibraryId), nameof(LibraryScanEntity.Status), nameof(LibraryScanEntity.CreatedOnUtc)])); + + // Assert + Assert.Equal([true, false, true], index.IsDescending); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryScanEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryScanEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanResultConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanResultConfigurationTests.cs new file mode 100644 index 00000000..fd1b8abf --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanResultConfigurationTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanResultConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanResultConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("LibraryScanResults", tableName); + Assert.Equal([nameof(LibraryScanResultEntity.LibraryScanId), nameof(LibraryScanResultEntity.Path)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!; + + // Act + IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.Path)); + IProperty statusProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.Status)); + IProperty fileSizeProperty = entityType.GetProperty(nameof(LibraryScanResultEntity.FileSize)); + + // Assert + Assert.False(pathProperty.IsNullable); + Assert.Equal(1024, pathProperty.GetMaxLength()); + Assert.Equal(typeof(LibraryScanFileStatus), statusProperty.ClrType); + Assert.Equal("TEXT", statusProperty.GetColumnType()); + Assert.Equal(10, statusProperty.GetMaxLength()); + Assert.False(fileSizeProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!; + + // Act + IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(LibraryScanEntity), foreignKey.PrincipalEntityType.ClrType); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + Assert.Equal(nameof(LibraryScanResultEntity.LibraryScanId), foreignKey.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexes() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanResultEntity))!; + + // Act + List indexes = [.. entityType.GetIndexes()]; + + // Assert + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanResultEntity.ContentHash), nameof(LibraryScanResultEntity.FileSize), nameof(LibraryScanResultEntity.Path)])); + Assert.Contains(indexes, index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(LibraryScanResultEntity.Path)])); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanSnapshotConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanSnapshotConfigurationTests.cs new file mode 100644 index 00000000..710902d8 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanSnapshotConfigurationTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanSnapshotConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanSnapshotConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("LibraryScanSnapshots", tableName); + Assert.Equal([nameof(LibraryScanSnapshotEntity.LibraryId), nameof(LibraryScanSnapshotEntity.Path)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!; + + // Act + IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.Path)); + IProperty contentHashProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.ContentHash)); + + // Assert + Assert.False(pathProperty.IsNullable); + Assert.Equal(1024, pathProperty.GetMaxLength()); + Assert.False(contentHashProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!; + + // Act + IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(LibraryEntity), foreignKey.PrincipalEntityType.ClrType); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + Assert.Equal(nameof(LibraryScanSnapshotEntity.LibraryId), foreignKey.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes()); + + // Assert + Assert.Equal(nameof(LibraryScanSnapshotEntity.LibraryId), index.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanSnapshotEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(LibraryScanSnapshotEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanStagingResultsConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanStagingResultsConfigurationTests.cs new file mode 100644 index 00000000..b69895c0 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryScanStagingResultsConfigurationTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanStagingResultsConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanStagingResultsConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("LibraryScanStagingResults", tableName); + Assert.Equal([nameof(LibraryScanStagingResultsEntity.LibraryScanId), nameof(LibraryScanStagingResultsEntity.Path)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!; + + // Act + IProperty pathProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.Path)); + IProperty needsRehashProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.NeedsRehash)); + IProperty isNewProperty = entityType.GetProperty(nameof(LibraryScanStagingResultsEntity.IsNew)); + + // Assert + Assert.False(pathProperty.IsNullable); + Assert.Equal(1024, pathProperty.GetMaxLength()); + Assert.False(needsRehashProperty.IsNullable); + Assert.False(isNewProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!; + + // Act + IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(LibraryScanEntity), foreignKey.PrincipalEntityType.ClrType); + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + Assert.Equal(nameof(LibraryScanStagingResultsEntity.LibraryScanId), foreignKey.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureIndexOnLibraryScanIdAndNeedsRehash() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(LibraryScanStagingResultsEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes()); + + // Assert + Assert.Equal([nameof(LibraryScanStagingResultsEntity.LibraryScanId), nameof(LibraryScanStagingResultsEntity.NeedsRehash)], index.Properties.Select(property => property.Name)); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PermissionConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PermissionConfigurationTests.cs new file mode 100644 index 00000000..a53715ed --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PermissionConfigurationTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PermissionConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public PermissionConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Permissions", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigurePermissionNameAsRequiredString() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!; + + // Act + IProperty permissionNameProperty = entityType.GetProperty(nameof(PermissionEntity.PermissionName)); + + // Assert + Assert.False(permissionNameProperty.IsNullable); + Assert.Equal(100, permissionNameProperty.GetMaxLength()); + Assert.Equal(typeof(AuthorizationPermission), permissionNameProperty.ClrType); + Assert.Equal("TEXT", permissionNameProperty.GetColumnType()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PermissionEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PermissionEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PermissionEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PluginConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PluginConfigurationTests.cs new file mode 100644 index 00000000..e44f5d1f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PluginConfigurationTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public PluginConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Plugins", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!; + + // Act + IProperty nameProperty = entityType.GetProperty(nameof(PluginEntity.Name)); + IProperty authorProperty = entityType.GetProperty(nameof(PluginEntity.Author)); + IProperty versionProperty = entityType.GetProperty(nameof(PluginEntity.Version)); + IProperty loadStatusProperty = entityType.GetProperty(nameof(PluginEntity.LoadStatus)); + + // Assert + Assert.False(nameProperty.IsNullable); + Assert.Equal(255, nameProperty.GetMaxLength()); + Assert.False(authorProperty.IsNullable); + Assert.Equal(255, authorProperty.GetMaxLength()); + Assert.False(versionProperty.IsNullable); + Assert.Equal(50, versionProperty.GetMaxLength()); + Assert.Equal(typeof(PluginLoadStatus), loadStatusProperty.ClrType); + Assert.Equal("TEXT", loadStatusProperty.GetColumnType()); + Assert.Equal(20, loadStatusProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PluginEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PluginEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PluginEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RoleConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RoleConfigurationTests.cs new file mode 100644 index 00000000..fb32afe6 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RoleConfigurationTests.cs @@ -0,0 +1,73 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RoleConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public RoleConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Roles", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRoleNameAsRequired() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!; + + // Act + IProperty roleNameProperty = entityType.GetProperty(nameof(RoleEntity.RoleName)); + + // Assert + Assert.False(roleNameProperty.IsNullable); + Assert.Equal(100, roleNameProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RoleEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(RoleEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(RoleEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RolePermissionConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RolePermissionConfigurationTests.cs new file mode 100644 index 00000000..84e799da --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/RolePermissionConfigurationTests.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RolePermissionConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public RolePermissionConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("RolePermissions", tableName); + Assert.Equal([nameof(RolePermissionEntity.RoleId), nameof(RolePermissionEntity.PermissionId)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldIgnoreTheIdProperty() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!; + + // Act + IProperty? idProperty = entityType.FindProperty(nameof(RolePermissionEntity.Id)); + + // Assert + Assert.Null(idProperty); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!; + + // Act + List foreignKeys = entityType.GetForeignKeys().ToList(); + + // Assert + Assert.Equal(2, foreignKeys.Count); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(RoleEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(PermissionEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnRoleIdAndPermissionId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(RolePermissionEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(RolePermissionEntity.RoleId), nameof(RolePermissionEntity.PermissionId)])); + + // Assert + Assert.True(index.IsUnique); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TagConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TagConfigurationTests.cs new file mode 100644 index 00000000..ef0d95bd --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/TagConfigurationTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TagConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public TagConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TagEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Tags", tableName); + Assert.Equal([nameof(TagEntity.Name)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureNameAsRequired() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(TagEntity))!; + + // Act + IProperty nameProperty = entityType.GetProperty(nameof(TagEntity.Name)); + + // Assert + Assert.False(nameProperty.IsNullable); + Assert.Equal(50, nameProperty.GetMaxLength()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserConfigurationTests.cs new file mode 100644 index 00000000..3ff87938 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserConfigurationTests.cs @@ -0,0 +1,115 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public UserConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Users", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!; + + // Act + IProperty usernameProperty = entityType.GetProperty(nameof(UserEntity.Username)); + IProperty passwordProperty = entityType.GetProperty(nameof(UserEntity.Password)); + IProperty tempPasswordProperty = entityType.GetProperty(nameof(UserEntity.TempPassword)); + IProperty totpSecretProperty = entityType.GetProperty(nameof(UserEntity.TotpSecret)); + + // Assert + Assert.False(usernameProperty.IsNullable); + Assert.Equal(255, usernameProperty.GetMaxLength()); + Assert.False(passwordProperty.IsNullable); + Assert.Null(tempPasswordProperty.GetDefaultValue()); + Assert.Null(totpSecretProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!; + + // Act + List navigations = entityType.GetNavigations().ToList(); + List referencingForeignKeys = entityType.GetReferencingForeignKeys().ToList(); + + // Assert + Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.Libraries) && navigation.IsCollection); + Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.UserRole) && !navigation.IsCollection); + Assert.Contains(navigations, navigation => navigation.Name == nameof(UserEntity.UserPermissions) && navigation.IsCollection); + Assert.All(referencingForeignKeys, foreignKey => Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUsername() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!; + + // Act + IIndex? usernameIndex = entityType.GetIndexes().SingleOrDefault(index => index.Properties.Any(property => property.Name == nameof(UserEntity.Username))); + + // Assert + Assert.NotNull(usernameIndex); + Assert.True(usernameIndex!.IsUnique); + Assert.Equal(nameof(UserEntity.Username), usernameIndex.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(UserEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(UserEntity.UpdatedBy)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + Assert.Null(updatedByProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserPermissionConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserPermissionConfigurationTests.cs new file mode 100644 index 00000000..d5a4d3f8 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserPermissionConfigurationTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserPermissionConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public UserPermissionConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndCompositeKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("UserPermissions", tableName); + Assert.Equal([nameof(UserPermissionEntity.UserId), nameof(UserPermissionEntity.PermissionId)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldIgnoreTheIdProperty() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!; + + // Act + IProperty? idProperty = entityType.FindProperty(nameof(UserPermissionEntity.Id)); + + // Assert + Assert.Null(idProperty); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + Assert.Equal(2, foreignKeys.Count); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(PermissionEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserIdAndPermissionId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserPermissionEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(UserPermissionEntity.UserId), nameof(UserPermissionEntity.PermissionId)])); + + // Assert + Assert.True(index.IsUnique); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserRoleConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserRoleConfigurationTests.cs new file mode 100644 index 00000000..ae444931 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserRoleConfigurationTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Authorization; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserRoleConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public UserRoleConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("UserRoles", tableName); + Assert.Equal([nameof(UserRoleEntity.UserId)], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldIgnoreTheIdProperty() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!; + + // Act + IProperty? idProperty = entityType.FindProperty(nameof(UserRoleEntity.Id)); + + // Assert + Assert.Null(idProperty); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureRelationshipsWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + Assert.Equal(2, foreignKeys.Count); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(UserEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + Assert.Contains(foreignKeys, foreignKey => foreignKey.PrincipalEntityType.ClrType == typeof(RoleEntity) && foreignKey.DeleteBehavior == DeleteBehavior.Cascade); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserIdAndRoleId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!; + + // Act + IIndex index = Assert.Single(entityType.GetIndexes(), candidate => candidate.Properties.Select(property => property.Name).SequenceEqual([nameof(UserRoleEntity.UserId), nameof(UserRoleEntity.RoleId)])); + + // Assert + Assert.True(index.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserRoleEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserRoleEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserRoleEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs new file mode 100644 index 00000000..2a7cec99 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs @@ -0,0 +1,107 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public UserSettingsConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("UserSettings", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureScalarPropertiesAsRequired() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + 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)); + + // Assert + Assert.False(userIdProperty.IsNullable); + Assert.False(isPaginationEnabledProperty.IsNullable); + Assert.False(itemsPerPageProperty.IsNullable); + Assert.False(ignoreThePrefixProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureOneToOneRelationshipWithUser() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + IForeignKey foreignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(DeleteBehavior.Cascade, foreignKey.DeleteBehavior); + Assert.Equal(typeof(UserEntity), foreignKey.PrincipalEntityType.ClrType); + Assert.Equal(nameof(UserSettingsEntity.UserId), foreignKey.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureUniqueIndexOnUserId() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + IIndex userIdIndex = Assert.Single(entityType.GetIndexes()); + + // Assert + Assert.True(userIdIndex.IsUnique); + Assert.Equal(nameof(UserSettingsEntity.UserId), userIdIndex.Properties[0].Name); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureAuditProperties() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(UserSettingsEntity))!; + + // Act + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.CreatedOnUtc)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(UserSettingsEntity.UpdatedOnUtc)); + + // Assert + Assert.False(createdOnUtcProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Interceptors/UpdateAuditableEntitiesInterceptorTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Interceptors/UpdateAuditableEntitiesInterceptorTests.cs new file mode 100644 index 00000000..2ef99d5f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Interceptors/UpdateAuditableEntitiesInterceptorTests.cs @@ -0,0 +1,150 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Common.Interceptors; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Interceptors; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateAuditableEntitiesInterceptorTests +{ + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDateTimeProvider _mockDateTimeProvider; + private readonly UpdateAuditableEntitiesInterceptor _sut; + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new(); + private readonly Guid _userId; + private readonly DateTime _fixedUtcNow; + + /// + /// Initializes a new instance of the class. + /// + public UpdateAuditableEntitiesInterceptorTests() + { + _userId = Guid.NewGuid(); + _fixedUtcNow = new DateTime(2026, 1, 15, 10, 30, 0, DateTimeKind.Utc); + _mockCurrentUserService = Substitute.For(); + _mockCurrentUserService.UserId.Returns(_userId); + _mockDateTimeProvider = Substitute.For(); + _mockDateTimeProvider.UtcNow.Returns(_fixedUtcNow); + _sut = new UpdateAuditableEntitiesInterceptor(_mockCurrentUserService, _mockDateTimeProvider); + } + + [Fact] + public async Task SavingChangesAsync_WhenAddingAuditableEntity_ShouldSetCreationProperties() + { + // Arrange + LuminaDbContext context = CreateContext(); + BookEntity book = _bookEntityFixture.Create(); + + // Act + context.Books.Add(book); + await context.SaveChangesAsync(); + + // Assert + Assert.Equal(_fixedUtcNow, book.CreatedOnUtc); + Assert.Equal(_userId, book.CreatedBy); + Assert.Null(book.UpdatedOnUtc); + Assert.Null(book.UpdatedBy); + } + + [Fact] + public async Task SavingChangesAsync_WhenModifyingAuditableEntity_ShouldSetModificationProperties() + { + // Arrange + LuminaDbContext context = CreateContext(); + BookEntity book = _bookEntityFixture.Create(); + context.Books.Add(book); + await context.SaveChangesAsync(); + + // Act + book.Title = "Updated Title"; + await context.SaveChangesAsync(); + + // Assert + Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc); + Assert.Equal(_userId, book.UpdatedBy); + Assert.Equal(_fixedUtcNow, book.CreatedOnUtc); + Assert.Equal(_userId, book.CreatedBy); + } + + [Fact] + public async Task SavingChangesAsync_WhenNoUserIsAuthenticated_ShouldUseGuidEmptyForCreationAndSystemUserForModification() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + LuminaDbContext context = CreateContext(); + BookEntity book = _bookEntityFixture.Create(); + context.Books.Add(book); + await context.SaveChangesAsync(); + + // Act + book.Title = "Updated Title"; + await context.SaveChangesAsync(); + + // Assert + Assert.Equal(Guid.Empty, book.CreatedBy); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), book.UpdatedBy); + Assert.Equal(_fixedUtcNow, book.UpdatedOnUtc); + } + + [Fact] + public void SavingChanges_WhenAddingAuditableEntity_ShouldSetCreationProperties() + { + // Arrange + LuminaDbContext context = CreateContext(); + BookEntity book = _bookEntityFixture.Create(); + + // Act + context.Books.Add(book); + context.SaveChanges(); + + // Assert + Assert.Equal(_fixedUtcNow, book.CreatedOnUtc); + Assert.Equal(_userId, book.CreatedBy); + Assert.Null(book.UpdatedOnUtc); + Assert.Null(book.UpdatedBy); + } + + [Fact] + public async Task SavingChangesAsync_WhenTrackingNonAuditableEntity_ShouldNotThrow() + { + // Arrange + LuminaDbContext context = CreateContext(); + LibraryScanResultEntity scanResult = _libraryScanResultEntityFixture.Create(); + + // Act + context.LibraryScanResults.Add(scanResult); + await context.SaveChangesAsync(); + + // Assert + Assert.Equal(EntityState.Unchanged, context.Entry(scanResult).State); + } + + /// + /// Creates a that uses the interceptor under test. + /// + /// A configured instance. + private LuminaDbContext CreateContext() + { + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .AddInterceptors(_sut) + .Options; + return new LuminaDbContext(options); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookAlphaFilterSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookAlphaFilterSpecificationTests.cs new file mode 100644 index 00000000..c59e1047 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookAlphaFilterSpecificationTests.cs @@ -0,0 +1,198 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.DataAccess.Core.Repositories.Books.Specifications; +using Lumina.DataAccess.Core.UoW; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications; + +/// +/// Contains unit tests for the class. +/// +/// +/// The specification builds an expression that uses the SQLite GLOB function, which can only be evaluated by the Entity Framework SQLite provider, +/// so the tests exercise the expression against a real SQLite database instead of evaluating it in memory. +/// +[ExcludeFromCodeCoverage] +public class BookAlphaFilterSpecificationTests : 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. + /// + public BookAlphaFilterSpecificationTests() + { + _connectionString = $"Data Source=luminadataccess-alphaspec-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + _anchorConnection = new SqliteConnection(_connectionString); + _anchorConnection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); + _context.Database.EnsureCreated(); + } + + [Fact] + public async Task ToExpression_WhenFilterAlphaKeyIsNull_ShouldMatchAllBooks() + { + // Arrange + List books = await SeedBooksAsync( + _bookEntityFixture.Create(title: "The Fellowship of the Ring"), + _bookEntityFixture.Create(title: "1984"), + _bookEntityFixture.Create(title: "@home")); + BookAlphaFilterSpecification specification = new(null, false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + Assert.Equal(3, matchingBooks.Count); + } + + [Fact] + public async Task ToExpression_WhenFilterAlphaKeyIsALetter_ShouldMatchTitlesStartingWithThatLetter() + { + // Arrange + List books = await SeedBooksAsync( + _bookEntityFixture.Create(title: "The Fellowship of the Ring"), + _bookEntityFixture.Create(title: "1984"), + _bookEntityFixture.Create(title: "Zoo")); + BookAlphaFilterSpecification specification = new("T", false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal(books[0].Id, matchedBook.Id); + } + + [Fact] + public async Task ToExpression_WhenFilterAlphaKeyIsALowercaseLetter_ShouldMatchTitlesStartingWithThatLetter() + { + // Arrange + await SeedBooksAsync( + _bookEntityFixture.Create(title: "Zoo"), + _bookEntityFixture.Create(title: "moby dick")); + BookAlphaFilterSpecification specification = new("Z", false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal("Zoo", matchedBook.Title); + } + + [Fact] + public async Task ToExpression_WhenFilterAlphaKeyIsNumber_ShouldMatchTitlesStartingWithADigit() + { + // Arrange + List books = await SeedBooksAsync( + _bookEntityFixture.Create(title: "1984"), + _bookEntityFixture.Create(title: "The Fellowship of the Ring")); + BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.NUMBER, false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal(books[0].Id, matchedBook.Id); + } + + [Fact] + public async Task ToExpression_WhenFilterAlphaKeyIsSymbol_ShouldMatchTitlesStartingWithANonAlphanumericCharacter() + { + // Arrange + List books = await SeedBooksAsync( + _bookEntityFixture.Create(title: "@home"), + _bookEntityFixture.Create(title: "1984"), + _bookEntityFixture.Create(title: "Zoo")); + BookAlphaFilterSpecification specification = new(LibraryItemAlphaKeys.SYMBOL, false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal(books[0].Id, matchedBook.Id); + } + + [Fact] + public async Task ToExpression_WhenIgnoreThePrefixIsTrue_ShouldStripTheLeadingThePrefix() + { + // Arrange + List books = await SeedBooksAsync( + _bookEntityFixture.Create(title: "The Fellowship of the Ring"), + _bookEntityFixture.Create(title: "To Kill a Mockingbird")); + BookAlphaFilterSpecification specification = new("T", true); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal(books[1].Id, matchedBook.Id); + } + + [Fact] + public async Task ToExpression_WhenIgnoreThePrefixIsFalse_ShouldNotStripTheLeadingThePrefix() + { + // Arrange + await SeedBooksAsync( + _bookEntityFixture.Create(title: "The Fellowship of the Ring"), + _bookEntityFixture.Create(title: "To Kill a Mockingbird")); + BookAlphaFilterSpecification specification = new("T", false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + Assert.Equal(2, matchingBooks.Count); + } + + [Fact] + public async Task ToExpression_WhenTitleIsEmpty_ShouldFallBackToOriginalTitle() + { + // Arrange + await SeedBooksAsync(_bookEntityFixture.Create(title: string.Empty, originalTitle: "The Real Title")); + BookAlphaFilterSpecification specification = new("T", false); + + // Act + List matchingBooks = await _context.Books.Where(specification.ToExpression()).ToListAsync(); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal("The Real Title", matchedBook.OriginalTitle); + } + + /// + /// Persists the provided books to the database. + /// + /// The books to persist. + /// The persisted books. + private async Task> SeedBooksAsync(params BookEntity[] books) + { + _context.Books.AddRange(books); + await _context.SaveChangesAsync(); + return [.. books]; + } + + /// + public void Dispose() + { + _context.Dispose(); + _anchorConnection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookSearchSpecificationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookSearchSpecificationTests.cs new file mode 100644 index 00000000..a2ca276f --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/Specifications/BookSearchSpecificationTests.cs @@ -0,0 +1,118 @@ +#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.Repositories.Books.Specifications; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Books.Specifications; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookSearchSpecificationTests +{ + private readonly BookEntityFixture _bookEntityFixture = new(); + + [Fact] + public void ToExpression_WhenTitleContainsSearchTerm_ShouldMatchBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "The Fellowship of the Ring"; + book.OriginalTitle = null; + BookSearchSpecification specification = new("Fellowship"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenOriginalTitleContainsSearchTerm_ShouldMatchBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "A Random Title"; + book.OriginalTitle = "Lord of the Rings: The Fellowship"; + BookSearchSpecification specification = new("Fellowship"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenOriginalTitleIsNull_ShouldMatchOnlyOnTitle() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "The Fellowship of the Ring"; + book.OriginalTitle = null; + BookSearchSpecification specification = new("Ring"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.True(result); + } + + [Fact] + public void ToExpression_WhenNeitherTitleNorOriginalTitleContainsSearchTerm_ShouldNotMatchBook() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "The Fellowship of the Ring"; + book.OriginalTitle = "The Two Towers"; + BookSearchSpecification specification = new("Hobbit"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToExpression_WhenSearchTermIsNotPresent_ShouldFilterOutNonMatchingBooks() + { + // Arrange + List books = _bookEntityFixture.CreateMany(3); + books[0].Title = "The Fellowship of the Ring"; + books[1].Title = "The Two Towers"; + books[2].Title = "The Return of the King"; + BookSearchSpecification specification = new("Fellowship"); + + // Act + IEnumerable matchingBooks = books.AsQueryable().Where(specification.ToExpression()); + + // Assert + BookEntity matchedBook = Assert.Single(matchingBooks); + Assert.Equal(books[0].Title, matchedBook.Title); + } + + [Fact] + public void ToExpression_WhenTitleMatchesInDifferentCase_ShouldNotMatchCaseInsensitively() + { + // Arrange + BookEntity book = _bookEntityFixture.Create(); + book.Title = "The Fellowship of the Ring"; + book.OriginalTitle = null; + BookSearchSpecification specification = new("fellowship"); + + // Act + bool result = specification.IsSatisfiedBy(book); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs new file mode 100644 index 00000000..7a4bbb14 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/DirectoryScanFingerprintRepositoryTests.cs @@ -0,0 +1,181 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Common.Dapper; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +/// +/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database +/// instead of the mocked in-memory context used by the Entity Framework based repositories. +/// +[ExcludeFromCodeCoverage] +public class DirectoryScanFingerprintRepositoryTests : IDisposable +{ + private readonly string _connectionString; + private readonly SqliteConnection _anchorConnection; + private readonly LuminaDbContext _context; + private readonly DirectoryScanFingerprintRepository _sut; + private readonly DirectoryScanFingerprintEntityFixture _directoryScanFingerprintEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DirectoryScanFingerprintRepositoryTests() + { + DapperTypeHandlers.Register(); + _connectionString = $"Data Source=luminadataccess-fingerprint-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + _anchorConnection = new SqliteConnection(_connectionString); + _anchorConnection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); + _context.Database.EnsureCreated(); + _sut = new DirectoryScanFingerprintRepository(_context); + } + + [Fact] + public async Task GetMappedByLibraryIdAsync_WhenCalled_ShouldReturnFingerprintsOfTheLibraryMappedByPath() + { + // Arrange + (Guid libraryId, _) = await SeedLibraryGraphAsync(); + UserEntity otherUser = _userEntityFixture.Create(); + _context.Users.Add(otherUser); + Guid otherLibraryId = Guid.NewGuid(); + LibraryEntity otherLibrary = _libraryEntityFixture.Create(id: otherLibraryId, userId: otherUser.Id); + _context.Libraries.Add(otherLibrary); + + DirectoryScanFingerprintEntity firstFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1)); + DirectoryScanFingerprintEntity secondFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir2", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-2)); + DirectoryScanFingerprintEntity fingerprintOfOtherLibrary = _directoryScanFingerprintEntityFixture.Create(libraryId: otherLibraryId, path: "/dir3"); + _context.DirectoryScanFingerprints.AddRange(firstFingerprint, secondFingerprint, fingerprintOfOtherLibrary); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.True(result.Value.ContainsKey("/dir1")); + Assert.True(result.Value.ContainsKey("/dir2")); + Assert.False(result.Value.ContainsKey("/dir3")); + Assert.Equal(firstFingerprint.Id, result.Value["/dir1"].Id); + Assert.Equal(secondFingerprint.Id, result.Value["/dir2"].Id); + } + + [Fact] + public async Task GetMappedByLibraryIdAsync_WhenNoFingerprintsExist_ShouldReturnEmptyDictionary() + { + // Arrange + (Guid libraryId, _) = await SeedLibraryGraphAsync(); + + // Act + Result> result = await _sut.GetMappedByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task UpsertRangeAsync_WhenCalledWithNewFingerprints_ShouldInsertThemAndReturnUpdated() + { + // Arrange + (Guid libraryId, _) = await SeedLibraryGraphAsync(); + List fingerprints = + [ + _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId), + _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId) + ]; + + // Act + Result result = await _sut.UpsertRangeAsync(fingerprints, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.Equal(2, await _context.DirectoryScanFingerprints.CountAsync()); + } + + [Fact] + public async Task UpsertRangeAsync_WhenCalledWithExistingFingerprints_ShouldUpdateTheirLastWriteTime() + { + // Arrange + (Guid libraryId, _) = await SeedLibraryGraphAsync(); + DirectoryScanFingerprintEntity existingFingerprint = _directoryScanFingerprintEntityFixture.Create(libraryId: libraryId, path: "/dir1", lastWriteTimeUtc: DateTime.UtcNow.AddDays(-1)); + _context.DirectoryScanFingerprints.Add(existingFingerprint); + await _context.SaveChangesAsync(); + + DateTime newLastWriteTimeUtc = DateTime.UtcNow.AddDays(1); + DirectoryScanFingerprintEntity updatedFingerprint = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + Path = "/dir1", + LastWriteTimeUtc = newLastWriteTimeUtc + }; + + // Act + Result result = await _sut.UpsertRangeAsync([updatedFingerprint], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + DirectoryScanFingerprintEntity retrievedFingerprint = await _context.DirectoryScanFingerprints.AsNoTracking().SingleAsync(); + Assert.Equal(newLastWriteTimeUtc, retrievedFingerprint.LastWriteTimeUtc); + } + + [Fact] + public async Task UpsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnUpdatedWithoutUpserting() + { + // Arrange + (Guid libraryId, _) = await SeedLibraryGraphAsync(); + + // Act + Result result = await _sut.UpsertRangeAsync([], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.False(await _context.DirectoryScanFingerprints.AnyAsync()); + } + + /// + /// Seeds the user and media library required by the foreign key of the fingerprints table. + /// + /// The seeded library Id and user Id. + private async Task<(Guid LibraryId, Guid UserId)> SeedLibraryGraphAsync() + { + UserEntity user = _userEntityFixture.Create(); + _context.Users.Add(user); + LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id); + _context.Libraries.Add(library); + await _context.SaveChangesAsync(); + return (library.Id, user.Id); + } + + /// + public void Dispose() + { + _context.Dispose(); + _anchorConnection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs new file mode 100644 index 00000000..0ff25b41 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryRepositoryTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly LibraryRepository _sut; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new LibraryRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenLibraryDoesNotExist_ShouldAddLibraryToContextAndReturnCreated() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(library, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedLibrary = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == library.Id); + Assert.NotNull(addedLibrary); + } + + [Fact] + public async Task InsertAsync_WhenLibraryAlreadyExists_ShouldReturnError() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(library, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByIdAsync_WhenLibraryExists_ShouldReturnLibraryWithContentLocations() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(library.Id, result.Value!.Id); + Assert.Equal(library.ContentLocations.Count, result.Value.ContentLocations.Count); + } + + [Fact] + public async Task GetByIdAsync_WhenLibraryDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetAllEnabledAsync_WhenCalled_ShouldReturnOnlyEnabledLibraries() + { + // Arrange + LibraryEntity enabledLibrary = _libraryEntityFixture.Create(isEnabled: true); + LibraryEntity disabledLibrary = _libraryEntityFixture.Create(isEnabled: false); + _mockContext.Libraries.AddRange(enabledLibrary, disabledLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllEnabledAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryEntity retrievedLibrary = Assert.Single(result.Value); + Assert.Equal(enabledLibrary.Id, retrievedLibrary.Id); + } + + [Fact] + public async Task GetAllEnabledAndUnlockedAsync_WhenCalled_ShouldReturnOnlyEnabledAndUnlockedLibraries() + { + // Arrange + LibraryEntity enabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: false); + LibraryEntity enabledLockedLibrary = _libraryEntityFixture.Create(isEnabled: true, isLocked: true); + LibraryEntity disabledUnlockedLibrary = _libraryEntityFixture.Create(isEnabled: false, isLocked: false); + _mockContext.Libraries.AddRange(enabledUnlockedLibrary, enabledLockedLibrary, disabledUnlockedLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllEnabledAndUnlockedAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryEntity retrievedLibrary = Assert.Single(result.Value); + Assert.Equal(enabledUnlockedLibrary.Id, retrievedLibrary.Id); + } + + [Fact] + public async Task GetAllAsync_WhenCalled_ShouldReturnAllLibraries() + { + // Arrange + List libraries = _libraryEntityFixture.CreateMany(3); + _mockContext.Libraries.AddRange(libraries); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetAllAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(3, result.Value.Count()); + Assert.Equal(libraries, result.Value); + } + + [Fact] + public async Task UpdateAsync_WhenLibraryExists_ShouldUpdateScalarPropertiesAndContentLocations() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(contentLocations: ["/old/path"]); + _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 + }; + + // Act + Result result = await _sut.UpdateAsync(updatedLibrary, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryEntity? retrievedLibrary = await _mockContext.Libraries.FindAsync(library.Id); + Assert.NotNull(retrievedLibrary); + Assert.Equal("Updated Title", retrievedLibrary!.Title); + Assert.Single(retrievedLibrary.ContentLocations); + Assert.Equal("/new/path", retrievedLibrary.ContentLocations.First().Path); + } + + [Fact] + public async Task UpdateAsync_WhenLibraryDoesNotExist_ShouldReturnError() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(library, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + } + + [Fact] + public async Task DeleteByIdAsync_WhenLibraryExists_ShouldRemoveItFromContextAndReturnDeleted() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + _mockContext.Libraries.Add(library); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByIdAsync(library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + + EntityEntry? deletedLibrary = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Deleted && entityEntry.Entity.Id == library.Id); + Assert.NotNull(deletedLibrary); + } + + [Fact] + public async Task DeleteByIdAsync_WhenLibraryDoesNotExist_ShouldReturnError() + { + // Act + Result result = await _sut.DeleteByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs new file mode 100644 index 00000000..ebeb3f10 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanRepositoryTests.cs @@ -0,0 +1,191 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly LibraryScanRepository _sut; + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new LibraryScanRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenLibraryScanDoesNotExist_ShouldAddScanToContextAndReturnCreated() + { + // Arrange + LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(libraryScan, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedScan = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScan.Id); + Assert.NotNull(addedScan); + } + + [Fact] + public async Task InsertAsync_WhenLibraryScanAlreadyExists_ShouldReturnError() + { + // Arrange + LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create(); + _mockContext.LibraryScans.Add(libraryScan); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.InsertAsync(libraryScan, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryScanAlreadyExists, result.FirstError); + Assert.Single(_mockContext.ChangeTracker.Entries()); + } + + [Fact] + public async Task GetByIdAsync_WhenLibraryScanExists_ShouldReturnScanWithLibraryAndUser() + { + // Arrange + LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create(); + _mockContext.LibraryScans.Add(libraryScan); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByIdAsync(libraryScan.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.NotNull(result.Value); + Assert.Equal(libraryScan.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByIdAsync_WhenLibraryScanDoesNotExist_ShouldReturnNull() + { + // Act + Result result = await _sut.GetByIdAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task GetPastMonthScansByLibraryIdAsync_WhenCalled_ShouldReturnOnlyRecentScansOfTheLibrary() + { + // Arrange + LibraryEntity library = _libraryEntityFixture.Create(); + LibraryScanEntity recentScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddDays(-1)); + LibraryScanEntity oldScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, createdOnUtc: DateTime.UtcNow.AddMonths(-2)); + LibraryScanEntity scanOfAnotherLibrary = _libraryScanEntityFixture.Create(createdOnUtc: DateTime.UtcNow.AddDays(-1)); + _mockContext.LibraryScans.AddRange(recentScan, oldScan, scanOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetPastMonthScansByLibraryIdAsync(library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryScanEntity retrievedScan = Assert.Single(result.Value); + Assert.Equal(recentScan.Id, retrievedScan.Id); + } + + [Fact] + public async Task GetRunningScansAsync_WhenCalled_ShouldReturnOnlyRunningScans() + { + // Arrange + LibraryScanEntity runningScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScanEntity completedScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Completed); + LibraryScanEntity pendingScan = _libraryScanEntityFixture.Create(status: LibraryScanJobStatus.Pending); + _mockContext.LibraryScans.AddRange(runningScan, completedScan, pendingScan); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetRunningScansAsync(CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryScanEntity retrievedScan = Assert.Single(result.Value); + Assert.Equal(runningScan.Id, retrievedScan.Id); + } + + [Fact] + public async Task UpdateAsync_WhenLibraryScanExists_ShouldUpdateItsScalarProperties() + { + // Arrange + LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create(); + _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 + }; + + // Act + Result result = await _sut.UpdateAsync(updatedScan, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryScanEntity? retrievedScan = await _mockContext.LibraryScans.FindAsync(libraryScan.Id); + Assert.NotNull(retrievedScan); + Assert.Equal(LibraryScanJobStatus.Completed, retrievedScan!.Status); + } + + [Fact] + public async Task UpdateAsync_WhenLibraryScanDoesNotExist_ShouldReturnError() + { + // Arrange + LibraryScanEntity libraryScan = _libraryScanEntityFixture.Create(); + + // Act + Result result = await _sut.UpdateAsync(libraryScan, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanResultRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanResultRepositoryTests.cs new file mode 100644 index 00000000..d0ff7134 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanResultRepositoryTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanResultRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly LibraryScanResultRepository _sut; + private readonly LibraryScanResultEntityFixture _libraryScanResultEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanResultRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new LibraryScanResultRepository(_mockContext); + } + + [Fact] + public async Task InsertAsync_WhenCalled_ShouldAddScanResultToContextAndReturnCreated() + { + // Arrange + LibraryScanResultEntity libraryScanResult = _libraryScanResultEntityFixture.Create(); + + // Act + Result result = await _sut.InsertAsync(libraryScanResult, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + + EntityEntry? addedScanResult = _mockContext.ChangeTracker.Entries() + .FirstOrDefault(entityEntry => entityEntry.State == EntityState.Added && entityEntry.Entity.Id == libraryScanResult.Id); + Assert.NotNull(addedScanResult); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs new file mode 100644 index 00000000..e3212529 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanSnapshotRepositoryTests.cs @@ -0,0 +1,246 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +/// +/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database +/// instead of the mocked in-memory context used by the Entity Framework based repositories. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanSnapshotRepositoryTests : IDisposable +{ + private readonly string _connectionString; + private readonly SqliteConnection _anchorConnection; + private readonly LuminaDbContext _context; + private readonly LibraryScanSnapshotRepository _sut; + private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new(); + private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanSnapshotRepositoryTests() + { + _connectionString = $"Data Source=luminadataccess-snapshot-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + _anchorConnection = new SqliteConnection(_connectionString); + _anchorConnection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); + _context.Database.EnsureCreated(); + _sut = new LibraryScanSnapshotRepository(_context); + } + + [Fact] + public async Task GetDeletedPathsAsync_WhenSnapshotPathsAreMissingFromStaging_ShouldReturnThosePaths() + { + // Arrange + (_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub"); + LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub"); + _context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot); + LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub"); + _context.LibraryScanStagingResults.Add(staging); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string deletedPath = Assert.Single(result.Value); + Assert.Equal("/books/delete.epub", deletedPath); + } + + [Fact] + public async Task GetDeletedPathsAsync_WhenAllSnapshotPathsArePresentInStaging_ShouldReturnEmptyList() + { + // Arrange + (_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub"); + _context.LibraryScanSnapshots.Add(snapshot); + LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/keep.epub"); + _context.LibraryScanStagingResults.Add(staging); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetDeletedPathsAsync_WhenStagingOfAnotherScanMatches_ShouldStillReturnThePaths() + { + // Arrange + (UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed); + _context.LibraryScans.Add(otherScan); + LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub"); + _context.LibraryScanSnapshots.Add(snapshot); + LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id, path: "/books/a.epub"); + _context.LibraryScanStagingResults.Add(stagingOfOtherScan); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetDeletedPathsAsync(library.Id, scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + string deletedPath = Assert.Single(result.Value); + Assert.Equal("/books/a.epub", deletedPath); + } + + [Fact] + public async Task GetPathsAsync_WhenCalled_ShouldReturnAllSnapshotPathsOfTheLibrary() + { + // Arrange + (_, LibraryEntity library, _) = await SeedScanGraphAsync(); + LibraryScanSnapshotEntity firstSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub"); + LibraryScanSnapshotEntity secondSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/b.epub"); + _context.LibraryScanSnapshots.AddRange(firstSnapshot, secondSnapshot); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Contains("/books/a.epub", result.Value); + Assert.Contains("/books/b.epub", result.Value); + } + + [Fact] + public async Task GetPathsAsync_WhenNoSnapshotsExist_ShouldReturnEmptyList() + { + // Arrange + (_, LibraryEntity library, _) = await SeedScanGraphAsync(); + + // Act + Result> result = await _sut.GetPathsAsync(library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task ApplySnapshotSwapAsync_WhenCalled_ShouldAuditDeletedChangedAndNewItemsAndUpdateSnapshot() + { + // Arrange + (UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + + LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000); + LibraryScanSnapshotEntity deletedSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/delete.epub", contentHash: 222, fileSize: 200, ticks: 2000); + _context.LibraryScanSnapshots.AddRange(keptSnapshot, deletedSnapshot); + + LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create( + libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, contentHash: 999, needsRehash: false, isNew: false); + LibraryScanStagingResultsEntity newStaging = _libraryScanStagingResultsEntityFixture.Create( + libraryScanId: scanId, path: "/books/new.epub", size: 300, ticks: 3000, contentHash: 300, needsRehash: true, isNew: true); + LibraryScanStagingResultsEntity modifiedStaging = _libraryScanStagingResultsEntityFixture.Create( + libraryScanId: scanId, path: "/books/modified.epub", size: 400, ticks: 4000, contentHash: 400, needsRehash: true, isNew: false); + _context.LibraryScanStagingResults.AddRange(unchangedStaging, newStaging, modifiedStaging); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + // audit entries: deleted, new and modified items + List scanResults = await _context.LibraryScanResults.AsNoTracking() + .Where(scanResult => scanResult.LibraryScanId == scanId) + .ToListAsync(); + Assert.Equal(3, scanResults.Count); + Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/delete.epub" && scanResult.Status == LibraryScanFileStatus.Deleted); + Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/new.epub" && scanResult.Status == LibraryScanFileStatus.New); + Assert.Contains(scanResults, scanResult => scanResult.Path == "/books/modified.epub" && scanResult.Status == LibraryScanFileStatus.Modified); + Assert.DoesNotContain(scanResults, scanResult => scanResult.Path == "/books/keep.epub"); + + // the snapshot now contains the kept, new and modified items and no longer contains the deleted one + List snapshots = await _context.LibraryScanSnapshots.AsNoTracking() + .Where(snapshot => snapshot.LibraryId == library.Id) + .ToListAsync(); + Assert.Equal(3, snapshots.Count); + Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/keep.epub" && snapshot.ContentHash == 111); + Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/new.epub" && snapshot.ContentHash == 300); + Assert.Contains(snapshots, snapshot => snapshot.Path == "/books/modified.epub" && snapshot.ContentHash == 400); + Assert.DoesNotContain(snapshots, snapshot => snapshot.Path == "/books/delete.epub"); + + // the staging results of the scan have been cleared + Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId)); + } + + [Fact] + public async Task ApplySnapshotSwapAsync_WhenNoStagingNeedsRehash_ShouldOnlyClearStagingAndAuditDeletedItems() + { + // Arrange + (UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + + LibraryScanSnapshotEntity keptSnapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/keep.epub", contentHash: 111, fileSize: 100, ticks: 1000); + _context.LibraryScanSnapshots.Add(keptSnapshot); + LibraryScanStagingResultsEntity unchangedStaging = _libraryScanStagingResultsEntityFixture.Create( + libraryScanId: scanId, path: "/books/keep.epub", size: 100, ticks: 1000, needsRehash: false, isNew: false); + _context.LibraryScanStagingResults.Add(unchangedStaging); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.ApplySnapshotSwapAsync(library.Id, scanId, user.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.False(await _context.LibraryScanResults.AsNoTracking().AnyAsync()); + Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId)); + } + + /// + /// Seeds the user, media library and media library scan required by the foreign keys of the snapshot and staging tables. + /// + /// The seeded user, media library and scan Id. + private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync() + { + UserEntity user = _userEntityFixture.Create(); + _context.Users.Add(user); + LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id); + _context.Libraries.Add(library); + LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running); + _context.LibraryScans.Add(scan); + await _context.SaveChangesAsync(); + return (user, library, scan.Id); + } + + /// + public void Dispose() + { + _context.Dispose(); + _anchorConnection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs new file mode 100644 index 00000000..7e0759cf --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Libraries/LibraryScanStagingResultsRepositoryTests.cs @@ -0,0 +1,298 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +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.DataAccess.Core.Repositories.Libraries; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Libraries; + +/// +/// Contains unit tests for the class. +/// +/// +/// The repository executes parameterized raw SQL on a dedicated database connection, so the tests exercise it against a real SQLite database +/// instead of the mocked in-memory context used by the Entity Framework based repositories. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanStagingResultsRepositoryTests : IDisposable +{ + private readonly string _connectionString; + private readonly SqliteConnection _anchorConnection; + private readonly LuminaDbContext _context; + private readonly LibraryScanStagingResultsRepository _sut; + private readonly LibraryScanStagingResultsEntityFixture _libraryScanStagingResultsEntityFixture = new(); + private readonly LibraryScanSnapshotEntityFixture _libraryScanSnapshotEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryScanEntityFixture _libraryScanEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public LibraryScanStagingResultsRepositoryTests() + { + _connectionString = $"Data Source=luminadataccess-staging-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + _anchorConnection = new SqliteConnection(_connectionString); + _anchorConnection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); + _context.Database.EnsureCreated(); + _sut = new LibraryScanStagingResultsRepository(_context); + } + + [Fact] + public async Task InsertRangeAsync_WhenCalled_ShouldInsertAllEntitiesAndReturnCreated() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + List stagingResults = _libraryScanStagingResultsEntityFixture.CreateMany(3); + for (int i = 0; i < stagingResults.Count; i++) + stagingResults[i] = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId); + + // Act + Result result = await _sut.InsertRangeAsync(stagingResults, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Equal(3, await _context.LibraryScanStagingResults.CountAsync()); + } + + [Fact] + public async Task InsertRangeAsync_WhenCollectionIsEmpty_ShouldReturnCreatedWithoutInserting() + { + // Arrange + await SeedScanGraphAsync(); + + // Act + Result result = await _sut.InsertRangeAsync([], CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.False(await _context.LibraryScanStagingResults.AnyAsync()); + } + + [Fact] + public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasSameSizeAndTicks_ShouldMarkAsUnchanged() + { + // Arrange + (_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 111, fileSize: 100, ticks: 1000); + _context.LibraryScanSnapshots.Add(snapshot); + LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 100, ticks: 1000); + _context.LibraryScanStagingResults.Add(staging); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync(); + Assert.Equal(111UL, markedStaging.ContentHash); + Assert.Equal(111UL, markedStaging.PreviousContentHash); + Assert.False(markedStaging.NeedsRehash); + Assert.False(markedStaging.IsNew); + } + + [Fact] + public async Task MarkChangesAgainstSnapshotAsync_WhenSnapshotHasDifferentSizeOrTicks_ShouldMarkAsChanged() + { + // Arrange + (_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanSnapshotEntity snapshot = _libraryScanSnapshotEntityFixture.Create(libraryId: library.Id, path: "/books/a.epub", contentHash: 222, fileSize: 100, ticks: 1000); + _context.LibraryScanSnapshots.Add(snapshot); + LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 500, ticks: 5000); + _context.LibraryScanStagingResults.Add(staging); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync(); + Assert.Equal(222UL, markedStaging.ContentHash); + Assert.Equal(222UL, markedStaging.PreviousContentHash); + Assert.True(markedStaging.NeedsRehash); + Assert.False(markedStaging.IsNew); + } + + [Fact] + public async Task MarkChangesAgainstSnapshotAsync_WhenNoSnapshotExists_ShouldKeepTheItemMarkedAsNew() + { + // Arrange + (_, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + // the file system discovery job seeds new items with no hash and marks them as new, needing a rehash + LibraryScanStagingResultsEntity staging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 0, previousContentHash: 0, needsRehash: true, isNew: true); + _context.LibraryScanStagingResults.Add(staging); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.MarkChangesAgainstSnapshotAsync(scanId, library.Id, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + LibraryScanStagingResultsEntity markedStaging = await _context.LibraryScanStagingResults.AsNoTracking().SingleAsync(); + Assert.Equal(0UL, markedStaging.ContentHash); + Assert.Equal(0UL, markedStaging.PreviousContentHash); + Assert.True(markedStaging.NeedsRehash); + Assert.True(markedStaging.IsNew); + } + + [Fact] + public async Task GetFilesToHashCountAsync_WhenCalled_ShouldReturnOnlyStagingResultsNeedingRehash() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity firstRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true); + LibraryScanStagingResultsEntity secondRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: true); + LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, needsRehash: false); + _context.LibraryScanStagingResults.AddRange(firstRehash, secondRehash, noRehash); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.GetFilesToHashCountAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value); + } + + [Fact] + public async Task GetFilesToHashPageAsync_WhenCalled_ShouldReturnOrderedPageOfStagingResultsNeedingRehash() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", size: 10, ticks: 100, needsRehash: true); + LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", size: 20, ticks: 200, needsRehash: true); + LibraryScanStagingResultsEntity noRehash = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/z.epub", needsRehash: false); + _context.LibraryScanStagingResults.AddRange(aFile, bFile, noRehash); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetFilesToHashPageAsync(scanId, null, 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal("/books/a.epub", result.Value[0].Path); + Assert.Equal("/books/b.epub", result.Value[1].Path); + Assert.Equal(10, result.Value[0].Size); + Assert.Equal(20, result.Value[1].Size); + Assert.Equal(100, result.Value[0].Ticks); + Assert.Equal(200, result.Value[1].Ticks); + } + + [Fact] + public async Task GetFilesToHashPageAsync_WhenLastPathProvided_ShouldReturnOnlyResultsAfterIt() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity aFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", needsRehash: true); + LibraryScanStagingResultsEntity bFile = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", needsRehash: true); + _context.LibraryScanStagingResults.AddRange(aFile, bFile); + await _context.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetFilesToHashPageAsync(scanId, "/books/a.epub", 10, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + HashedFileSystemFileDto retrievedFile = Assert.Single(result.Value); + Assert.Equal("/books/b.epub", retrievedFile.Path); + } + + [Fact] + public async Task UpdateFileHashesAsync_WhenCalled_ShouldUpdateTheContentHashes() + { + // Arrange + (_, _, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanStagingResultsEntity firstStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/a.epub", contentHash: 111); + LibraryScanStagingResultsEntity secondStaging = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId, path: "/books/b.epub", contentHash: 222); + _context.LibraryScanStagingResults.AddRange(firstStaging, secondStaging); + await _context.SaveChangesAsync(); + + 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 } + ]; + + // Act + Result result = await _sut.UpdateFileHashesAsync(scanId, hashedFiles, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + + List stagingResults = await _context.LibraryScanStagingResults.AsNoTracking().OrderBy(staging => staging.Path).ToListAsync(); + Assert.Equal(999UL, stagingResults[0].ContentHash); + Assert.Equal(888UL, stagingResults[1].ContentHash); + } + + [Fact] + public async Task ClearForScanAsync_WhenCalled_ShouldRemoveOnlyTheStagingResultsOfTheScan() + { + // Arrange + (UserEntity user, LibraryEntity library, Guid scanId) = await SeedScanGraphAsync(); + LibraryScanEntity otherScan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Completed); + _context.LibraryScans.Add(otherScan); + LibraryScanStagingResultsEntity stagingOfScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: scanId); + LibraryScanStagingResultsEntity stagingOfOtherScan = _libraryScanStagingResultsEntityFixture.Create(libraryScanId: otherScan.Id); + _context.LibraryScanStagingResults.AddRange(stagingOfScan, stagingOfOtherScan); + await _context.SaveChangesAsync(); + + // Act + Result result = await _sut.ClearForScanAsync(scanId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.False(await _context.LibraryScanStagingResults.AsNoTracking().AnyAsync(staging => staging.LibraryScanId == scanId)); + Assert.Single(await _context.LibraryScanStagingResults.AsNoTracking().Where(staging => staging.LibraryScanId == otherScan.Id).ToListAsync()); + } + + /// + /// Seeds the user, media library and media library scan required by the foreign keys of the staging table. + /// + /// The seeded user, media library and scan Id. + private async Task<(UserEntity User, LibraryEntity Library, Guid ScanId)> SeedScanGraphAsync() + { + UserEntity user = _userEntityFixture.Create(); + _context.Users.Add(user); + LibraryEntity library = _libraryEntityFixture.Create(userId: user.Id); + _context.Libraries.Add(library); + LibraryScanEntity scan = _libraryScanEntityFixture.Create(libraryId: library.Id, libraryEntity: library, userId: user.Id, status: LibraryScanJobStatus.Running); + _context.LibraryScans.Add(scan); + await _context.SaveChangesAsync(); + return (user, library, scan.Id); + } + + /// + public void Dispose() + { + _context.Dispose(); + _anchorConnection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs new file mode 100644 index 00000000..aa080525 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs @@ -0,0 +1,108 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.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; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.UoW; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LuminaDbContextTests : IDisposable +{ + private readonly string _connectionString; + private readonly SqliteConnection _anchorConnection; + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public LuminaDbContextTests() + { + _connectionString = $"Data Source=luminadataccess-dbcontext-tests-{Guid.NewGuid()};Mode=Memory;Cache=Shared"; + _anchorConnection = new SqliteConnection(_connectionString); + _anchorConnection.Open(); + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite(_connectionString).Options); + } + + [Fact] + public void OnModelCreating_WhenCalled_ShouldApplyAllEntityConfigurationsFromTheAssembly() + { + // Arrange + IModel model = _context.Model; + + // Act + string[] tableNames = [.. model.GetEntityTypes().Select(entityType => entityType.GetTableName()).OfType().OrderBy(name => name)]; + + // Assert + // The count assertion fails when a table is added or removed, reminding to update the assertions below. + Assert.Equal(23, tableNames.Length); + Assert.Contains("Books", tableNames); + Assert.Contains("Users", tableNames); + Assert.Contains("UserSettings", tableNames); + Assert.Contains("Roles", tableNames); + Assert.Contains("Permissions", tableNames); + Assert.Contains("UserRoles", tableNames); + Assert.Contains("UserPermissions", tableNames); + Assert.Contains("RolePermissions", tableNames); + Assert.Contains("Libraries", tableNames); + Assert.Contains("LibraryScans", tableNames); + Assert.Contains("LibraryScanResults", tableNames); + Assert.Contains("LibraryScanSnapshots", tableNames); + Assert.Contains("LibraryScanStagingResults", tableNames); + Assert.Contains("DirectoryScanFingerprints", tableNames); + Assert.Contains("Plugins", tableNames); + Assert.Contains("LibraryMetadataProviderConfigurations", tableNames); + Assert.Contains("Tags", tableNames); + Assert.Contains("Genres", tableNames); + Assert.Contains("LibraryContentLocations", tableNames); + Assert.Contains("BookTags", tableNames); + Assert.Contains("BookGenres", tableNames); + Assert.Contains("BookRatings", tableNames); + Assert.Contains("BookISBNs", tableNames); + } + + [Fact] + public async Task SaveChangesAsync_WhenAddingBook_ShouldPersistItToTheDatabase() + { + // 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 + }; + _context.Books.Add(book); + + // Act + await _context.SaveChangesAsync(); + + // Assert + BookEntity? retrievedBook = await _context.Books.FindAsync(book.Id); + Assert.NotNull(retrievedBook); + Assert.Equal("Test Book", retrievedBook!.Title); + } + + /// + public void Dispose() + { + _context.Dispose(); + _anchorConnection.Dispose(); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs new file mode 100644 index 00000000..9974f0b9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioContentTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class AudioContentTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void AudioContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + AudioContentType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (AudioContentType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + AudioContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs new file mode 100644 index 00000000..eaca2935 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/AudioLibrary/AudioRatingSourceTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.AudioLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class AudioRatingSourceTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void AudioRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + AudioRatingSource[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (AudioRatingSource value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + AudioRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs new file mode 100644 index 00000000..f733df6a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Authorization/AuthorizationPermissionTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Authorization; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class AuthorizationPermissionTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void AuthorizationPermission_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + AuthorizationPermission[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void None_WhenCastingToInteger_ShouldBeZero() + { + // Act + int value = (int)AuthorizationPermission.None; + + // Assert + Assert.Equal(0, value); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (AuthorizationPermission value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + AuthorizationPermission deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs new file mode 100644 index 00000000..fb847fae --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookFormatTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class BookFormatTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void BookFormat_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + BookFormat[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (BookFormat value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + BookFormat deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs new file mode 100644 index 00000000..1744a9f2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/BookRatingSourceTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class BookRatingSourceTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void BookRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + BookRatingSource[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (BookRatingSource value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + BookRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs new file mode 100644 index 00000000..91f47119 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/IsbnFormatTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class IsbnFormatTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void IsbnFormat_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + IsbnFormat[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (IsbnFormat value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + IsbnFormat deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs new file mode 100644 index 00000000..99393ae6 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/MetadataStatusTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class MetadataStatusTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void MetadataStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + MetadataStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (MetadataStatus value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + MetadataStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs new file mode 100644 index 00000000..e8b81ddd --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/BookLibrary/WrittenContentTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.BookLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void WrittenContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + WrittenContentType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (WrittenContentType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + WrittenContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs new file mode 100644 index 00000000..cc336912 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Common/SortOrderTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Common; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class SortOrderTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void SortOrder_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + SortOrder[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void Ascending_WhenCastingToInteger_ShouldBeZero() + { + // Act + int value = (int)SortOrder.Ascending; + + // Assert + Assert.Equal(0, value); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (SortOrder value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + SortOrder deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs new file mode 100644 index 00000000..3fc3d53c --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileAccessModeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class FileAccessModeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void FileAccessMode_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + FileAccessMode[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (FileAccessMode value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + FileAccessMode deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs new file mode 100644 index 00000000..d15ebe21 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemStatusTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemStatusTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void FileSystemItemStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + FileSystemItemStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (FileSystemItemStatus value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + FileSystemItemStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs new file mode 100644 index 00000000..8bc0abb0 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/FileSystemItemTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class FileSystemItemTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void FileSystemItemType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + FileSystemItemType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (FileSystemItemType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + FileSystemItemType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs new file mode 100644 index 00000000..07e2facc --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/FileSystem/PlatformTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.FileSystem; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlatformTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void PlatformType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlatformType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (PlatformType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + PlatformType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs new file mode 100644 index 00000000..804f53f5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanFileStatusTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFileStatusTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void LibraryScanFileStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + LibraryScanFileStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (LibraryScanFileStatus value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + LibraryScanFileStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs new file mode 100644 index 00000000..6831483b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryScanJobStatusTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanJobStatusTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void LibraryScanJobStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + LibraryScanJobStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (LibraryScanJobStatus value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + LibraryScanJobStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs new file mode 100644 index 00000000..72cffd07 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/LibraryTypeTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class LibraryTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void LibraryType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + LibraryType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void Book_WhenCastingToInteger_ShouldBeZero() + { + // Act + int value = (int)LibraryType.Book; + + // Assert + Assert.Equal(0, value); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (LibraryType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + LibraryType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs new file mode 100644 index 00000000..660fd599 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/MediaLibrary/MiscellaneousContentTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.MediaLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class MiscellaneousContentTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void MiscellaneousContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + MiscellaneousContentType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (MiscellaneousContentType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + MiscellaneousContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs new file mode 100644 index 00000000..14ffd398 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/ImageTypeTests.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class ImageTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void ImageType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + ImageType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void None_WhenCastingToInteger_ShouldBeZero() + { + // Act + int value = (int)ImageType.None; + + // Assert + Assert.Equal(0, value); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (ImageType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + ImageType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs new file mode 100644 index 00000000..13653fac --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/PhotoLibrary/VisualContentTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.PhotoLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class VisualContentTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void VisualContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + VisualContentType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (VisualContentType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + VisualContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs new file mode 100644 index 00000000..f68efa56 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginLoadStatusTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PluginLoadStatusTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void PluginLoadStatus_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PluginLoadStatus[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (PluginLoadStatus value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + PluginLoadStatus deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs new file mode 100644 index 00000000..ba05807b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Plugins/PluginSettingTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Plugins; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void PluginSettingType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PluginSettingType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (PluginSettingType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + PluginSettingType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs new file mode 100644 index 00000000..0aaa4dc7 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Primitives/ErrorTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Primitives; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class ErrorTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void ErrorType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + ErrorType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (ErrorType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + ErrorType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs new file mode 100644 index 00000000..040d5e45 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoContentTypeTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.VideoLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class VideoContentTypeTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void VideoContentType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + VideoContentType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (VideoContentType value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + VideoContentType deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs new file mode 100644 index 00000000..53eeb246 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/VideoLibrary/VideoRatingSourceTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.VideoLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.VideoLibrary; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class VideoRatingSourceTests +{ + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + [Fact] + public void VideoRatingSource_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + VideoRatingSource[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + Assert.All(values, value => Assert.True(Enum.IsDefined(value))); + } + + [Fact] + public void RoundTrip_WhenSerializingWithCamelCaseConverter_ShouldPreserveEnumValue() + { + // Arrange + foreach (VideoRatingSource value in Enum.GetValues()) + { + // Act + string json = JsonSerializer.Serialize(value, _jsonOptions); + VideoRatingSource deserialized = JsonSerializer.Deserialize(json, _jsonOptions); + + // Assert + Assert.Equal(value, deserialized); + Assert.StartsWith("\"", json, StringComparison.Ordinal); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj new file mode 100644 index 00000000..ed70b364 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Lumina.Domain.SharedKernel.UnitTests.csproj @@ -0,0 +1,40 @@ + + + + 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.Domain.UnitTests/Common/Errors/ErrorsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs new file mode 100644 index 00000000..2cc0c0af --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Errors/ErrorsTests.cs @@ -0,0 +1,179 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Errors; + +/// +/// Contains unit tests for the static catalog classes. +/// +[ExcludeFromCodeCoverage] +public class ErrorsTests +{ + [Fact] + public void LibraryScanning_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(16, typeof(DomainErrors.LibraryScanning).GetProperties().Length); + AssertError(DomainErrors.LibraryScanning.LibraryScanIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.CanOnlyStartPendingScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.CanOnlyCompleteRunningScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.CanOnlyCancelRunningScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.CanOnlyFailRunningScans, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.ScanIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.LibraryScanAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.LibraryScanning.LibraryAlreadyBeingScanned, ErrorType.Forbidden); + AssertError(DomainErrors.LibraryScanning.LibraryScanNotFound, ErrorType.NotFound); + AssertError(DomainErrors.LibraryScanning.TotalScanJobItemsCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.TotalScanJobsCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, ErrorType.Validation); + AssertError(DomainErrors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void Library_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(14, typeof(DomainErrors.Library).GetProperties().Length); + AssertError(DomainErrors.Library.CannotScanLockedLibrary, ErrorType.Forbidden); + AssertError(DomainErrors.Library.CannotScanDisabledLibrary, ErrorType.Forbidden); + AssertError(DomainErrors.Library.LibraryIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Library.FilterMustIncludeLibraryId, ErrorType.Validation); + AssertError(DomainErrors.Library.InvalidFilterAlphaKey, ErrorType.Validation); + AssertError(DomainErrors.Library.LibraryAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.Library.LibraryNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Library.LibraryTypeCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Library.CoverFileMustBeAnImage, ErrorType.Validation); + AssertError(DomainErrors.Library.UnknownLibraryType, ErrorType.Unexpected); + AssertError(DomainErrors.Library.PathsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Library.PathsListCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Library.TitleCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Library.TitleMustBeMaximum255CharactersLong, ErrorType.Validation); + } + + [Fact] + public void Users_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(3, typeof(DomainErrors.Users).GetProperties().Length); + AssertError(DomainErrors.Users.UserAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.Users.UserDoesNotExist, ErrorType.NotFound); + AssertError(DomainErrors.Users.UserIdCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void UserSettings_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(3, typeof(DomainErrors.UserSettings).GetProperties().Length); + AssertError(DomainErrors.UserSettings.UserSettingsAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.UserSettings.UserSettingsNotFound, ErrorType.NotFound); + AssertError(DomainErrors.UserSettings.ItemsPerPageMustBeGreaterThanZero, ErrorType.Validation); + } + + [Fact] + public void Metadata_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + { + // Assert + AssertError(DomainErrors.Metadata.MetadataCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TitleCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.OriginalReleaseYearMustBeBetween1And9999, ErrorType.Validation); + AssertError(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, ErrorType.Validation); + AssertError(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingValueMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, ErrorType.Validation); + AssertError(DomainErrors.Metadata.RatingVoteCountMustBePositive, ErrorType.Validation); + AssertError(DomainErrors.Metadata.InvalidIsoCode, ErrorType.Validation); + AssertError(DomainErrors.Metadata.GenreNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.TagNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void WrittenContent_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + { + // Assert + AssertError(DomainErrors.WrittenContent.BookAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidIsbn10Format, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.InvalidIsbn13Format, ErrorType.Validation); + AssertError(DomainErrors.WrittenContent.UnknownIsbnFormat, ErrorType.Unexpected); + AssertError(DomainErrors.WrittenContent.TheBookIsAlreadyInTheSeries, ErrorType.Forbidden); + AssertError(DomainErrors.WrittenContent.TheBookIsNotInTheSeries, ErrorType.Forbidden); + AssertError(DomainErrors.WrittenContent.BookNotFound, ErrorType.NotFound); + AssertError(DomainErrors.WrittenContent.PageCountMustBeGreaterThanZero, ErrorType.Validation); + } + + [Fact] + public void MediaContributor_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + { + // Assert + AssertError(DomainErrors.MediaContributor.ContributorsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorDisplayNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.RoleNameCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.RoleCategoryCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.MediaContributor.ContributorRoleCannotBeNull, ErrorType.Validation); + } + + [Fact] + public void FileSystemManagement_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + { + // Assert + AssertError(DomainErrors.FileSystemManagement.ParentNodeCannotBeNull, ErrorType.Failure); + AssertError(DomainErrors.FileSystemManagement.InvalidPath, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.PathCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.FileSystemManagement.FileNotFound, ErrorType.NotFound); + AssertError(DomainErrors.FileSystemManagement.FileAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.DirectoryAlreadyExists, ErrorType.Conflict); + AssertError(DomainErrors.FileSystemManagement.NameCannotBeEmpty, ErrorType.Validation); + } + + [Fact] + public void Thumbnails_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Equal(2, typeof(DomainErrors.Thumbnails).GetProperties().Length); + AssertError(DomainErrors.Thumbnails.NoThumbnail, ErrorType.Failure); + AssertError(DomainErrors.Thumbnails.ImageQualityMustBeBetweenZeroAndOneHundred, ErrorType.Validation); + } + + [Fact] + public void Permission_WhenAccessed_ShouldExposeErrorsWithExpectedTypes() + { + // Assert + // The count assertion fails when an error is added or removed, reminding to update the assertions below. + Assert.Single(typeof(DomainErrors.Permission).GetProperties()); + AssertError(DomainErrors.Permission.UnauthorizedAccess, ErrorType.Failure); + } + + [Fact] + public void Plugins_WhenAccessed_ShouldExposeRepresentativeErrorsWithExpectedTypes() + { + // Assert + AssertError(DomainErrors.Plugins.PluginNotFound, ErrorType.NotFound); + AssertError(DomainErrors.Plugins.PluginIdCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginIdsListCannotBeNull, ErrorType.Validation); + AssertError(DomainErrors.Plugins.PluginIdsListCannotBeEmpty, ErrorType.Validation); + AssertError(DomainErrors.Plugins.LibraryMetadataProviderConfigurationNotFound, ErrorType.NotFound); + } + + private static void AssertError(Error error, ErrorType expectedType) + { + Assert.Equal(expectedType, error.Type); + Assert.False(string.IsNullOrWhiteSpace(error.Code)); + Assert.False(string.IsNullOrWhiteSpace(error.Description)); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Exceptions/EventualConsistencyExceptionTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Exceptions/EventualConsistencyExceptionTests.cs new file mode 100644 index 00000000..d985e04a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Exceptions/EventualConsistencyExceptionTests.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Exceptions; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Exceptions; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EventualConsistencyExceptionTests +{ + [Fact] + public void Constructor_WhenCalledWithError_ShouldSetErrorAndMessage() + { + // Arrange + Error error = Error.Validation("Code", "The operation could not be completed."); + + // Act + EventualConsistencyException exception = new(error); + + // Assert + Assert.Equal(error, exception.EventualConsistencyError); + Assert.Equal(error.Description, exception.Message); + Assert.Empty(exception.UnderlyingErrors); + } + + [Fact] + public void Constructor_WhenCalledWithUnderlyingErrors_ShouldSetUnderlyingErrors() + { + // Arrange + Error primaryError = Error.Validation("Primary", "Primary error."); + List underlyingErrors = [Error.NotFound("Underlying1", "Underlying error 1."), Error.Conflict("Underlying2", "Underlying error 2.")]; + + // Act + EventualConsistencyException exception = new(primaryError, underlyingErrors); + + // Assert + Assert.Equal(primaryError, exception.EventualConsistencyError); + Assert.Equal(underlyingErrors, exception.UnderlyingErrors); + } + + [Fact] + public void Constructor_WhenUnderlyingErrorsAreNull_ShouldUseEmptyList() + { + // Act + EventualConsistencyException exception = new(Error.Failure("Code", "Description"), null); + + // Assert + Assert.NotNull(exception.UnderlyingErrors); + Assert.Empty(exception.UnderlyingErrors); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/AggregateRootTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/AggregateRootTests.cs new file mode 100644 index 00000000..954152db --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/AggregateRootTests.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Models.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AggregateRootTests +{ + [Fact] + public void GetDomainEvents_WhenNoEventsWereRaised_ShouldReturnEmptyList() + { + // Arrange + TestAggregateRoot aggregateRoot = new(Guid.NewGuid()); + + // Act + List domainEvents = aggregateRoot.GetDomainEvents(); + + // Assert + Assert.Empty(domainEvents); + } + + [Fact] + public void GetDomainEvents_WhenEventsWereRaised_ShouldReturnAllEvents() + { + // Arrange + TestAggregateRoot aggregateRoot = new(Guid.NewGuid()); + aggregateRoot.RaiseTestEvent(); + aggregateRoot.RaiseTestEvent(); + + // Act + List domainEvents = aggregateRoot.GetDomainEvents(); + + // Assert + Assert.Equal(2, domainEvents.Count); + Assert.All(domainEvents, domainEvent => Assert.IsType(domainEvent)); + } + + [Fact] + public void GetDomainEvents_WhenCalled_ShouldClearTheStoredEvents() + { + // Arrange + TestAggregateRoot aggregateRoot = new(Guid.NewGuid()); + aggregateRoot.RaiseTestEvent(); + + // Act + aggregateRoot.GetDomainEvents(); + List domainEvents = aggregateRoot.GetDomainEvents(); + + // Assert + Assert.Empty(domainEvents); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestAggregateRoot : AggregateRoot + { + /// + /// Initializes a new instance of the class. + /// + /// The id of the aggregate root. + public TestAggregateRoot(Guid id) : base(id) + { + } + + /// + /// Raises a on this aggregate root. + /// + public void RaiseTestEvent() + { + _domainEvents.Add(new TestDomainEvent(Guid.NewGuid(), DateTime.UtcNow)); + } + } + + /// + /// Test implementation of the interface. + /// + private sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent; +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs new file mode 100644 index 00000000..eb8794ac --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityIdTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Models.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EntityIdTests +{ + [Fact] + public void Value_WhenConstructed_ShouldBeSet() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + TestEntityId entityId = new(value); + + // Assert + Assert.Equal(value, entityId.Value); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnValueAsString() + { + // Arrange + Guid value = Guid.NewGuid(); + TestEntityId entityId = new(value); + + // Act + string? result = entityId.ToString(); + + // Assert + Assert.Equal(value.ToString(), result); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + TestEntityId firstId = new(value); + TestEntityId secondId = new(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + TestEntityId firstId = new(Guid.NewGuid()); + TestEntityId secondId = new(Guid.NewGuid()); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } + + [Fact] + public void GetHashCode_WithSameValue_ShouldReturnSameHashCode() + { + // Arrange + Guid value = Guid.NewGuid(); + TestEntityId firstId = new(value); + TestEntityId secondId = new(value); + + // Act + int firstHashCode = firstId.GetHashCode(); + int secondHashCode = secondId.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestEntityId : EntityId + { + /// + /// Initializes a new instance of the class. + /// + /// The value representing this object. + public TestEntityId(Guid value) : base(value) + { + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs new file mode 100644 index 00000000..5177711f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/EntityTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Models.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EntityTests +{ + [Fact] + public void Id_WhenConstructed_ShouldBeSet() + { + // Arrange + Guid id = Guid.NewGuid(); + + // Act + TestEntity entity = new(id); + + // Assert + Assert.Equal(id, entity.Id); + } + + [Fact] + public void Equals_WithSameId_ShouldReturnTrue() + { + // Arrange + Guid id = Guid.NewGuid(); + TestEntity firstEntity = new(id); + TestEntity secondEntity = new(id); + + // Act + bool result = firstEntity.Equals(secondEntity); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentId_ShouldReturnFalse() + { + // Arrange + TestEntity firstEntity = new(Guid.NewGuid()); + TestEntity secondEntity = new(Guid.NewGuid()); + + // Act + bool result = firstEntity.Equals(secondEntity); + + // Assert + Assert.False(result); + } + + [Fact] + public void EqualityOperator_WithSameId_ShouldReturnTrue() + { + // Arrange + Guid id = Guid.NewGuid(); + TestEntity firstEntity = new(id); + TestEntity secondEntity = new(id); + + // Act + bool result = firstEntity == secondEntity; + + // Assert + Assert.True(result); + } + + [Fact] + public void InequalityOperator_WithDifferentId_ShouldReturnTrue() + { + // Arrange + TestEntity firstEntity = new(Guid.NewGuid()); + TestEntity secondEntity = new(Guid.NewGuid()); + + // Act + bool result = firstEntity != secondEntity; + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameId_ShouldReturnSameHashCode() + { + // Arrange + Guid id = Guid.NewGuid(); + TestEntity firstEntity = new(id); + TestEntity secondEntity = new(id); + + // Act + int firstHashCode = firstEntity.GetHashCode(); + int secondHashCode = secondEntity.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + [Fact] + public void CreatedOnUtc_And_UpdatedOnUtc_WhenSet_ShouldBeStored() + { + // Arrange + TestEntity entity = new(Guid.NewGuid()); + DateTime createdOnUtc = new(2024, 1, 1, 12, 0, 0, DateTimeKind.Utc); + DateTime updatedOnUtc = new(2024, 1, 2, 12, 0, 0, DateTimeKind.Utc); + + // Act + entity.CreatedOnUtc = createdOnUtc; + entity.UpdatedOnUtc = updatedOnUtc; + + // Assert + Assert.Equal(createdOnUtc, entity.CreatedOnUtc); + Assert.Equal(updatedOnUtc, entity.UpdatedOnUtc); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestEntity : Entity + { + /// + /// Initializes a new instance of the class. + /// + /// The id of the entity. + public TestEntity(Guid id) : base(id) + { + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/ValueObjectTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/ValueObjectTests.cs new file mode 100644 index 00000000..5c2012a0 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Models/Core/ValueObjectTests.cs @@ -0,0 +1,164 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Models.Core; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Models.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ValueObjectTests +{ + [Fact] + public void Equals_WithSameComponents_ShouldReturnTrue() + { + // Arrange + TestValueObject firstValueObject = new("value"); + TestValueObject secondValueObject = new("value"); + + // Act + bool result = firstValueObject.Equals(secondValueObject); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentComponents_ShouldReturnFalse() + { + // Arrange + TestValueObject firstValueObject = new("first"); + TestValueObject secondValueObject = new("second"); + + // Act + bool result = firstValueObject.Equals(secondValueObject); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentType_ShouldReturnFalse() + { + // Arrange + TestValueObject valueObject = new("value"); + OtherTestValueObject otherValueObject = new("value"); + + // Act + bool result = valueObject.Equals(otherValueObject); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithNull_ShouldReturnFalse() + { + // Arrange + TestValueObject valueObject = new("value"); + + // Act + bool result = valueObject.Equals(null); + + // Assert + Assert.False(result); + } + + [Fact] + public void EqualityOperator_WithSameComponents_ShouldReturnTrue() + { + // Arrange + TestValueObject firstValueObject = new("value"); + TestValueObject secondValueObject = new("value"); + + // Act + bool result = firstValueObject == secondValueObject; + + // Assert + Assert.True(result); + } + + [Fact] + public void InequalityOperator_WithDifferentComponents_ShouldReturnTrue() + { + // Arrange + TestValueObject firstValueObject = new("first"); + TestValueObject secondValueObject = new("second"); + + // Act + bool result = firstValueObject != secondValueObject; + + // Assert + Assert.True(result); + } + + [Fact] + public void GetHashCode_WithSameComponents_ShouldReturnSameHashCode() + { + // Arrange + TestValueObject firstValueObject = new("value"); + TestValueObject secondValueObject = new("value"); + + // Act + int firstHashCode = firstValueObject.GetHashCode(); + int secondHashCode = secondValueObject.GetHashCode(); + + // Assert + Assert.Equal(firstHashCode, secondHashCode); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestValueObject : ValueObject + { + private readonly string _value; + + /// + /// Initializes a new instance of the class. + /// + /// The value of the value object. + public TestValueObject(string value) + { + _value = value; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return _value; + } + } + + /// + /// Concrete test implementation of the abstract class, with a different type. + /// + private sealed class OtherTestValueObject : ValueObject + { + private readonly string _value; + + /// + /// Initializes a new instance of the class. + /// + /// The value of the value object. + public OtherTestValueObject(string value) + { + _value = value; + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return _value; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ErrorTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ErrorTests.cs new file mode 100644 index 00000000..665f9228 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ErrorTests.cs @@ -0,0 +1,197 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Primitives; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Primitives; + +/// +/// Contains unit tests for the class and its derived error records. +/// +[ExcludeFromCodeCoverage] +public class ErrorTests +{ + [Fact] + public void NotFound_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.NotFound(); + + // Assert + AssertError(error, ErrorType.NotFound, "General.NotFound", "A 'Not Found' error has occurred."); + } + + [Fact] + public void NotFound_WhenCalledWithCodeAndDescription_ShouldUseProvidedValues() + { + // Act + Error error = Error.NotFound("Library.NotFound", "The library was not found."); + + // Assert + AssertError(error, ErrorType.NotFound, "Library.NotFound", "The library was not found."); + } + + [Fact] + public void InvalidOperation_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.InvalidOperation(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.InvalidOperation", "An invalid operation error has occurred."); + } + + [Fact] + public void Forbidden_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Forbidden(); + + // Assert + AssertError(error, ErrorType.Forbidden, "General.Forbidden", "A 'Forbidden' error has occurred."); + } + + [Fact] + public void Failure_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Failure(); + + // Assert + AssertError(error, ErrorType.Failure, "General.Failure", "A failure has occurred."); + } + + [Fact] + public void Validation_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Validation(); + + // Assert + AssertError(error, ErrorType.Validation, "General.Validation", "A validation error has occurred."); + } + + [Fact] + public void Validation_WhenCalledWithCodeAndDescription_ShouldUseProvidedValues() + { + // Act + Error error = Error.Validation("Title.CannotBeEmpty", "The title cannot be empty."); + + // Assert + AssertError(error, ErrorType.Validation, "Title.CannotBeEmpty", "The title cannot be empty."); + } + + [Fact] + public void Conflict_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Conflict(); + + // Assert + AssertError(error, ErrorType.Conflict, "General.Conflict", "A conflict error has occurred."); + } + + [Fact] + public void Timeout_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Timeout(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.Timeout", "The operation timed out."); + } + + [Fact] + public void Unauthorized_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Unauthorized(); + + // Assert + AssertError(error, ErrorType.Unauthorized, "General.Unauthorized", "An 'Unauthorized' error has occurred."); + } + + [Fact] + public void Unexpected_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Unexpected(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.Unexpected", "An unexpected error has occurred."); + } + + [Fact] + public void Internal_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.Internal(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.Internal", "An internal error has occurred."); + } + + [Fact] + public void ResourceUnavailable_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.ResourceUnavailable(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.ResourceUnavailable", "The required resource is currently unavailable."); + } + + [Fact] + public void NotImplemented_WhenCalledWithoutArguments_ShouldUseDefaultCodeAndDescription() + { + // Act + Error error = Error.NotImplemented(); + + // Assert + AssertError(error, ErrorType.Unexpected, "General.NotImplemented", "The requested functionality is not implemented."); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnRecordRepresentation() + { + // Arrange + Error error = Error.NotFound("Library.NotFound", "The library was not found."); + + // Act + string result = error.ToString(); + + // Assert + Assert.Equal("NotFoundError { Type = NotFound, Code = Library.NotFound, Description = The library was not found. }", result); + } + + [Fact] + public void Equals_WhenSameCodeAndDescription_ShouldReturnTrue() + { + // Act + Error firstError = Error.Validation("Code", "Description"); + Error secondError = Error.Validation("Code", "Description"); + + // Assert + Assert.Equal(firstError, secondError); + Assert.Equal(firstError.GetHashCode(), secondError.GetHashCode()); + } + + [Fact] + public void Equals_WhenDifferentCode_ShouldReturnFalse() + { + // Act + Error firstError = Error.Validation("Code1", "Description"); + Error secondError = Error.Validation("Code2", "Description"); + + // Assert + Assert.NotEqual(firstError, secondError); + } + + private static void AssertError(Error error, ErrorType expectedType, string expectedCode, string expectedDescription) + { + Assert.Equal(expectedType, error.Type); + Assert.Equal(expectedCode, error.Code); + Assert.Equal(expectedDescription, error.Description); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs new file mode 100644 index 00000000..00d40cc9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/Primitives/ResultTests.cs @@ -0,0 +1,377 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Common.Primitives; + +/// +/// Contains unit tests for the structure. +/// +[ExcludeFromCodeCoverage] +public class ResultTests +{ + [Fact] + public void Success_WhenCalledWithValue_ShouldCreateSuccessfulResult() + { + // Act + Result result = Result.Success("test"); + + // Assert + Assert.True(result.IsSuccess); + Assert.False(result.IsFailure); + Assert.Equal("test", result.Value); + } + + [Fact] + public void Failure_WhenCalledWithSingleError_ShouldCreateFailedResult() + { + // Arrange + Error error = Error.Validation("Code", "Description"); + + // Act + Result result = Result.Failure(error); + + // Assert + Assert.False(result.IsSuccess); + Assert.True(result.IsFailure); + Assert.Single(result.Errors); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public void Failure_WhenCalledWithMultipleErrors_ShouldCreateFailedResultWithAllErrors() + { + // Arrange + Error firstError = Error.Validation("Code1", "Description1"); + Error secondError = Error.NotFound("Code2", "Description2"); + + // Act + Result result = Result.Failure(new List([firstError, secondError])); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(2, result.Errors.Count); + Assert.Equal(firstError, result.Errors[0]); + Assert.Equal(secondError, result.Errors[1]); + Assert.Equal(firstError, result.FirstError); + } + + [Fact] + public void ImplicitConversion_WhenConvertingValue_ShouldCreateSuccessfulResult() + { + // Act + Result result = "test"; + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("test", result.Value); + } + + [Fact] + public void ImplicitConversion_WhenConvertingError_ShouldCreateFailedResult() + { + // Arrange + Error error = Error.Conflict("Code", "Description"); + + // Act + Result result = error; + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public void ImplicitConversion_WhenConvertingErrorList_ShouldCreateFailedResult() + { + // Arrange + List errors = [Error.Validation("Code", "Description")]; + + // Act + Result result = errors; + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(errors, result.Errors); + } + + [Fact] + public void Map_WhenResultIsSuccessful_ShouldMapValue() + { + // Arrange + Result result = Result.Success(5); + + // Act + Result mappedResult = result.Map(value => value.ToString()); + + // Assert + Assert.True(mappedResult.IsSuccess); + Assert.Equal("5", mappedResult.Value); + } + + [Fact] + public void Map_WhenResultIsFailed_ShouldPreserveErrors() + { + // Arrange + Error error = Error.Validation("Code", "Description"); + Result result = Result.Failure(error); + + // Act + Result mappedResult = result.Map(value => value.ToString()); + + // Assert + Assert.True(mappedResult.IsFailure); + Assert.Equal(error, mappedResult.FirstError); + } + + [Fact] + public void Bind_WhenResultIsSuccessful_ShouldReturnBinderResult() + { + // Arrange + Result result = Result.Success(5); + + // Act + Result boundResult = result.Bind(value => Result.Success(value.ToString())); + + // Assert + Assert.True(boundResult.IsSuccess); + Assert.Equal("5", boundResult.Value); + } + + [Fact] + public void Bind_WhenResultIsFailed_ShouldPreserveErrors() + { + // Arrange + Error error = Error.Validation("Code", "Description"); + Result result = Result.Failure(error); + + // Act + Result boundResult = result.Bind(value => Result.Success(value.ToString())); + + // Assert + Assert.True(boundResult.IsFailure); + Assert.Equal(error, boundResult.FirstError); + } + + [Fact] + public void OnSuccess_WhenResultIsSuccessful_ShouldExecuteAction() + { + // Arrange + Result result = Result.Success(5); + bool actionExecuted = false; + + // Act + result.OnSuccess(value => actionExecuted = true); + + // Assert + Assert.True(actionExecuted); + } + + [Fact] + public void OnSuccess_WhenResultIsFailed_ShouldNotExecuteAction() + { + // Arrange + Result result = Result.Failure(Error.Validation("Code", "Description")); + bool actionExecuted = false; + + // Act + result.OnSuccess(value => actionExecuted = true); + + // Assert + Assert.False(actionExecuted); + } + + [Fact] + public void OnFailure_WhenResultIsFailed_ShouldExecuteAction() + { + // Arrange + Error error = Error.Validation("Code", "Description"); + Result result = Result.Failure(error); + List? receivedErrors = null; + + // Act + result.OnFailure(errors => receivedErrors = [.. errors]); + + // Assert + Assert.NotNull(receivedErrors); + Assert.Single(receivedErrors); + Assert.Equal(error, receivedErrors[0]); + } + + [Fact] + public void OnFailure_WhenResultIsSuccessful_ShouldNotExecuteAction() + { + // Arrange + Result result = Result.Success(5); + bool actionExecuted = false; + + // Act + result.OnFailure(errors => actionExecuted = true); + + // Assert + Assert.False(actionExecuted); + } + + [Fact] + public void Match_WhenResultIsSuccessful_ShouldExecuteOnSuccessFunction() + { + // Arrange + Result result = Result.Success(5); + + // Act + string matchedResult = result.Match(value => $"Success: {value}", errors => "Failure"); + + // Assert + Assert.Equal("Success: 5", matchedResult); + } + + [Fact] + public void Match_WhenResultIsFailed_ShouldExecuteOnFailureFunction() + { + // Arrange + Result result = Result.Failure(Error.Validation("Code", "Description")); + + // Act + string matchedResult = result.Match(value => "Success", errors => $"Failure: {errors.Count}"); + + // Assert + Assert.Equal("Failure: 1", matchedResult); + } + + [Fact] + public void Value_WhenResultIsFailed_ShouldThrowInvalidOperationException() + { + // Arrange + Result result = Result.Failure(Error.Validation("Code", "Description")); + + // Act & Assert + Assert.Throws(() => result.Value); + } + + [Fact] + public void Errors_WhenResultIsSuccessful_ShouldThrowInvalidOperationException() + { + // Arrange + Result result = Result.Success("test"); + + // Act & Assert + Assert.Throws(() => result.Errors); + } + + [Fact] + public void Equals_WhenBothResultsAreSuccessfulWithSameValue_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Success("test"); + Result secondResult = Result.Success("test"); + + // Assert + Assert.True(firstResult.Equals(secondResult)); + } + + [Fact] + public void Equals_WhenResultsHaveDifferentSuccessValues_ShouldReturnFalse() + { + // Act + Result firstResult = Result.Success("first"); + Result secondResult = Result.Success("second"); + + // Assert + Assert.False(firstResult.Equals(secondResult)); + } + + [Fact] + public void Equals_WhenBothResultsAreFailedWithSameErrors_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Failure(Error.Validation("Code", "Description")); + Result secondResult = Result.Failure(Error.Validation("Code", "Description")); + + // Assert + Assert.True(firstResult.Equals(secondResult)); + } + + [Fact] + public void EqualityOperator_WhenResultsAreEqual_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Success(5); + Result secondResult = Result.Success(5); + + // Assert + Assert.True(firstResult == secondResult); + } + + [Fact] + public void InequalityOperator_WhenResultsAreNotEqual_ShouldReturnTrue() + { + // Act + Result firstResult = Result.Success(5); + Result secondResult = Result.Success(6); + + // Assert + Assert.True(firstResult != secondResult); + } + + [Fact] + public void GetHashCode_WhenResultsAreEqual_ShouldReturnSameHashCode() + { + // Act + Result firstResult = Result.Success(5); + Result secondResult = Result.Success(5); + + // Assert + Assert.Equal(firstResult.GetHashCode(), secondResult.GetHashCode()); + } + + [Fact] + public void ToString_WhenResultIsSuccessful_ShouldReturnSuccessString() + { + // Arrange + Result result = Result.Success("test"); + + // Act + string resultString = result.ToString(); + + // Assert + Assert.Equal("Success: test", resultString); + } + + [Fact] + public void ToString_WhenResultIsFailed_ShouldReturnFailureString() + { + // Arrange + Result result = Result.Failure(Error.Validation("Code", "Description")); + + // Act + string resultString = result.ToString(); + + // Assert + Assert.Equal("Failure: [ValidationError { Type = Validation, Code = Code, Description = Description }]", resultString); + } + + [Fact] + public void From_WhenCalledWithValue_ShouldCreateSuccessfulResult() + { + // Act + Result result = Result.From(5); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal(5, result.Value); + } + + [Fact] + public void Marker_WhenAccessed_ShouldExposePredefinedSuccessResults() + { + // Act & Assert + Assert.Equal(new Success(), Result.Success); + Assert.Equal(new Created(), Result.Created); + Assert.Equal(new Updated(), Result.Updated); + Assert.Equal(new Deleted(), Result.Deleted); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs new file mode 100644 index 00000000..813c16c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/BaseMetadataTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BaseMetadataTests +{ + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + [Fact] + public void Constructor_WhenCalledWithValidData_ShouldSetAllProperties() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + List genres = [_genreFixture.Create(name: "Science Fiction")]; + List tags = [_tagFixture.Create(name: "bestseller")]; + Optional language = Optional.Some(_languageInfoFixture.Create()); + + // Act + TestMetadata metadata = new( + "Dune", + Optional.Some("Dune (Original)"), + Optional.Some("A classic novel."), + releaseInfo, + genres, + tags, + language, + Optional.None()); + + // Assert + Assert.Equal("Dune", metadata.Title); + Assert.Equal("Dune (Original)", metadata.OriginalTitle.Value); + Assert.Equal("A classic novel.", metadata.Description.Value); + Assert.Equal(releaseInfo, metadata.ReleaseInfo); + Assert.Single(metadata.Genres); + Assert.Single(metadata.Tags); + Assert.True(metadata.Language.HasValue); + Assert.False(metadata.OriginalLanguage.HasValue); + } + + [Fact] + public void Constructor_WhenTitleIsNull_ShouldThrowArgumentNullException() + { + // Act & Assert + Assert.Throws(() => new TestMetadata( + null!, + Optional.None(), + Optional.None(), + _releaseInfoFixture.Create(), + [], + [], + Optional.None(), + Optional.None())); + } + + [Fact] + public void Equals_WithSameData_ShouldReturnTrue() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + List genres = [_genreFixture.Create(name: "Science Fiction")]; + List tags = [_tagFixture.Create(name: "bestseller")]; + + // Act + TestMetadata firstMetadata = new("Dune", Optional.None(), Optional.None(), releaseInfo, genres, tags, Optional.None(), Optional.None()); + TestMetadata secondMetadata = new("Dune", Optional.None(), Optional.None(), releaseInfo, genres, tags, Optional.None(), Optional.None()); + + // Assert + Assert.Equal(firstMetadata, secondMetadata); + } + + [Fact] + public void Equals_WithDifferentTitle_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + TestMetadata firstMetadata = new("Dune", Optional.None(), Optional.None(), releaseInfo, [], [], Optional.None(), Optional.None()); + TestMetadata secondMetadata = new("Foundation", Optional.None(), Optional.None(), releaseInfo, [], [], Optional.None(), Optional.None()); + + // Assert + Assert.NotEqual(firstMetadata, secondMetadata); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestMetadata : BaseMetadata + { + /// + /// Initializes a new instance of the class. + /// + /// The title of the media item. + /// The optional original title. + /// The optional description. + /// The release information. + /// The genres. + /// The tags. + /// The optional language. + /// The optional original language. + public TestMetadata( + string title, + Optional originalTitle, + Optional description, + ReleaseInfo releaseInfo, + List genres, + List tags, + Optional language, + Optional originalLanguage) + : base(title, originalTitle, description, releaseInfo, genres, tags, language, originalLanguage) + { + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + return base.GetEqualityComponents(); + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs new file mode 100644 index 00000000..957512d2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/GenreTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GenreTests +{ + private readonly GenreFixture _genreFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidName_ShouldCreateGenreWithTrimmedName() + { + // Act + Result result = Genre.Create(" Science Fiction "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Science Fiction", result.Value.Name); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = Genre.Create(name); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.GenreNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Equals_WithSameName_ShouldReturnTrue() + { + // Arrange + Genre firstGenre = _genreFixture.Create(name: "Science Fiction"); + Genre secondGenre = _genreFixture.Create(name: "Science Fiction"); + + // Act + bool result = firstGenre.Equals(secondGenre); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + Genre firstGenre = _genreFixture.Create(name: "Science Fiction"); + Genre secondGenre = _genreFixture.Create(name: "Fantasy"); + + // Act + bool result = firstGenre.Equals(secondGenre); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnName() + { + // Arrange + Genre genre = _genreFixture.Create(name: "Science Fiction"); + + // Act + string result = genre.ToString(); + + // Assert + Assert.Equal("Science Fiction", result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs new file mode 100644 index 00000000..61ac9093 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/LanguageInfoTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LanguageInfoTests +{ + private readonly LanguageInfoFixture _languageInfoFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateLanguageInfoWithLowercaseCode() + { + // Act + Result result = LanguageInfo.Create("EN", "English", Optional.Some("English")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("en", result.Value.LanguageCode); + Assert.Equal("English", result.Value.LanguageName); + Assert.True(result.Value.NativeName.HasValue); + Assert.Equal("English", result.Value.NativeName.Value); + } + + [Theory] + [InlineData(null)] // null language code + [InlineData("")] // empty language code + [InlineData(" ")] // whitespace language code + public void Create_WhenLanguageCodeIsNullOrWhitespace_ShouldReturnError(string? languageCode) + { + // Act + Result result = LanguageInfo.Create(languageCode, "English", Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.LanguageCodeCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData(null)] // null language name + [InlineData("")] // empty language name + [InlineData(" ")] // whitespace language name + public void Create_WhenLanguageNameIsNullOrWhitespace_ShouldReturnError(string? languageName) + { + // Act + Result result = LanguageInfo.Create("en", languageName, Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.LanguageNameCannotBeEmpty, result.FirstError); + } + + [Theory] + [InlineData("e")] // single character code + [InlineData("eng")] // three character code + [InlineData("english")] // long code + public void Create_WhenLanguageCodeIsNotTwoCharactersLong_ShouldReturnError(string languageCode) + { + // Act + Result result = LanguageInfo.Create(languageCode, "English", Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.InvalidIsoCode, result.FirstError); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnFormattedString() + { + // Arrange + LanguageInfo languageInfo = _languageInfoFixture.Create( + languageCode: "en", + languageName: "English", + nativeName: Optional.None()); + + // Act + string result = languageInfo.ToString(); + + // Assert + Assert.Equal("en - English", result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/RatingTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/RatingTests.cs new file mode 100644 index 00000000..380613ab --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/RatingTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RatingTests +{ + [Fact] + public void Constructor_WhenCalled_ShouldSetValueMaxValueAndVoteCount() + { + // Act + TestRating rating = new(value: 4.5m, maxValue: 5, voteCount: Optional.Some(100)); + + // Assert + Assert.Equal(4.5m, rating.Value); + Assert.Equal(5, rating.MaxValue); + Assert.True(rating.VoteCount.HasValue); + Assert.Equal(100, rating.VoteCount.Value); + } + + [Fact] + public void AsPercentage_WhenCalled_ShouldReturnValueAsPercentageOfMaxValue() + { + // Arrange + TestRating rating = new(value: 4.5m, maxValue: 5, voteCount: Optional.None()); + + // Act + decimal result = rating.AsPercentage(); + + // Assert + Assert.Equal(90, result); + } + + [Fact] + public void AsPercentage_WhenValueEqualsMaxValue_ShouldReturnOneHundred() + { + // Arrange + TestRating rating = new(value: 5, maxValue: 5, voteCount: Optional.None()); + + // Act + decimal result = rating.AsPercentage(); + + // Assert + Assert.Equal(100, result); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestRating : Rating + { + /// + /// Initializes a new instance of the class. + /// + /// The numeric value of the rating. + /// The maximum possible rating value. + /// The optional number of votes or reviews. + public TestRating(decimal value, decimal maxValue, Optional voteCount) : base(value, maxValue, voteCount) + { + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + yield return MaxValue; + yield return VoteCount; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/ReleaseInfoTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/ReleaseInfoTests.cs new file mode 100644 index 00000000..613198d5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/ReleaseInfoTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReleaseInfoTests +{ + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateReleaseInfo() + { + // Act + Result result = ReleaseInfo.Create( + Optional.Some(new DateOnly(2001, 9, 14)), + Optional.Some(2001), + Optional.Some(new DateOnly(2010, 6, 1)), + Optional.Some(2010), + Optional.Some("US"), + Optional.Some("Director's Cut")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(new DateOnly(2001, 9, 14), result.Value.OriginalReleaseDate.Value); + Assert.Equal(2001, result.Value.OriginalReleaseYear.Value); + Assert.Equal(new DateOnly(2010, 6, 1), result.Value.ReReleaseDate.Value); + Assert.Equal(2010, result.Value.ReReleaseYear.Value); + Assert.Equal("US", result.Value.ReleaseCountry.Value); + Assert.Equal("Director's Cut", result.Value.ReleaseVersion.Value); + } + + [Fact] + public void Create_WhenOnlyOriginalReleaseYearProvided_ShouldCreateReleaseInfo() + { + // Act + Result result = ReleaseInfo.Create( + Optional.None(), + Optional.Some(2001), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2001, result.Value.OriginalReleaseYear.Value); + Assert.False(result.Value.OriginalReleaseDate.HasValue); + } + + [Fact] + public void Create_WhenOriginalReleaseDateAndYearMismatch_ShouldReturnError() + { + // Act + Result result = ReleaseInfo.Create( + Optional.Some(new DateOnly(2001, 9, 14)), + Optional.Some(2002), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.OriginalReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void Create_WhenReReleaseDateAndYearMismatch_ShouldReturnError() + { + // Act + Result result = ReleaseInfo.Create( + Optional.None(), + Optional.None(), + Optional.Some(new DateOnly(2010, 6, 1)), + Optional.Some(2011), + Optional.None(), + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.ReReleaseDateAndYearMustMatch, result.FirstError); + } + + [Fact] + public void Create_WhenReReleaseDateIsEarlierThanOriginalReleaseDate_ShouldReturnError() + { + // Act + Result result = ReleaseInfo.Create( + Optional.Some(new DateOnly(2010, 6, 1)), + Optional.Some(2010), + Optional.Some(new DateOnly(2001, 9, 14)), + Optional.Some(2001), + Optional.None(), + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate, result.FirstError); + } + + [Fact] + public void Create_WhenReReleaseYearIsEarlierThanOriginalReleaseYear_ShouldReturnError() + { + // Act + Result result = ReleaseInfo.Create( + Optional.None(), + Optional.Some(2010), + Optional.None(), + Optional.Some(2001), + Optional.None(), + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs new file mode 100644 index 00000000..b441bcc8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Common/ValueObjects/Metadata/TagTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Common.ValueObjects.Metadata; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TagTests +{ + private readonly TagFixture _tagFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidName_ShouldCreateTagWithTrimmedName() + { + // Act + Result result = Tag.Create(" bestseller "); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("bestseller", result.Value.Name); + } + + [Theory] + [InlineData(null)] // null name + [InlineData("")] // empty name + [InlineData(" ")] // whitespace name + public void Create_WhenNameIsNullOrWhitespace_ShouldReturnError(string? name) + { + // Act + Result result = Tag.Create(name); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.TagNameCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Equals_WithSameName_ShouldReturnTrue() + { + // Arrange + Tag firstTag = _tagFixture.Create(name: "bestseller"); + Tag secondTag = _tagFixture.Create(name: "bestseller"); + + // Act + bool result = firstTag.Equals(secondTag); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + Tag firstTag = _tagFixture.Create(name: "bestseller"); + Tag secondTag = _tagFixture.Create(name: "award-winning"); + + // Act + bool result = firstTag.Equals(secondTag); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnName() + { + // Arrange + Tag tag = _tagFixture.Create(name: "bestseller"); + + // Act + string result = tag.ToString(); + + // Assert + Assert.Equal("bestseller", result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataTests.cs new file mode 100644 index 00000000..0526d841 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/AudioLibraryBoundedContext/AudioLibraryAggregate/ValueObjects/AudioMetadataTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.AudioLibraryBoundedContext.AudioLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AudioMetadataTests +{ + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly AudioMetadataFixture _audioMetadataFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet() + { + // Act + Result result = AudioMetadata.Create( + "Abbey Road", + Optional.None(), + durationInSeconds: 2826, + sampleRate: 44100, + channels: 2, + _releaseInfoFixture.Create(), + Optional.Some("The last recorded album by the Beatles."), + [_genreFixture.Create(name: "Rock")], + [_tagFixture.Create(name: "classic")], + Optional.None(), + Optional.None(), + Optional.Some(16), + Optional.Some("PCM"), + Optional.Some(1411)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Abbey Road", result.Value.Title); + Assert.Equal(2826, result.Value.DurationInSeconds); + Assert.Equal(44100, result.Value.SampleRate); + Assert.Equal(2, result.Value.Channels); + Assert.Equal("The last recorded album by the Beatles.", result.Value.Description.Value); + Assert.Equal(16, result.Value.BitDepth.Value); + Assert.Equal("PCM", result.Value.AudioCodec.Value); + Assert.Equal(1411, result.Value.Bitrate.Value); + Assert.Single(result.Value.Genres); + Assert.Single(result.Value.Tags); + } + + [Fact] + public void Create_WhenCalledWithOptionalValuesAbsent_ShouldCreateMetadataWithoutThem() + { + // Act + Result result = AudioMetadata.Create( + "Abbey Road", + Optional.None(), + durationInSeconds: 2826, + sampleRate: 44100, + channels: 2, + _releaseInfoFixture.Create(), + Optional.None(), + [], + [], + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.BitDepth.HasValue); + Assert.False(result.Value.AudioCodec.HasValue); + Assert.False(result.Value.Bitrate.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Abbey Road", + originalTitle: Optional.None(), + durationInSeconds: 2826, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Abbey Road", + originalTitle: Optional.None(), + durationInSeconds: 2826, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + + // Assert + Assert.Equal(firstResult, secondResult); + } + + [Fact] + public void Equals_WithDifferentSampleRate_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + AudioMetadata firstResult = _audioMetadataFixture.Create( + title: "Abbey Road", + originalTitle: Optional.None(), + durationInSeconds: 2826, + sampleRate: 44100, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + AudioMetadata secondResult = _audioMetadataFixture.Create( + title: "Abbey Road", + originalTitle: Optional.None(), + durationInSeconds: 2826, + sampleRate: 48000, + channels: 2, + releaseInfo: releaseInfo, + description: Optional.None(), + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + bitDepth: Optional.None(), + audioCodec: Optional.None(), + bitrate: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs index d7455fcf..6610e6b7 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/DirectoryTests.cs @@ -4,7 +4,8 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; -using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; @@ -18,6 +19,10 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBound [ExcludeFromCodeCoverage] public class DirectoryTests { + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly DirectoryFixture _directoryFixture = new(); + private readonly FileFixture _fileFixture = new(); + [Fact] public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() { @@ -60,9 +65,7 @@ public class DirectoryTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - Result pathIdResult = FileSystemPathId.Create("/valid/path"); - Assert.False(pathIdResult.IsFailure); - FileSystemPathId pathId = pathIdResult.Value; + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "/valid/path"); string name = "TestDirectory"; Optional dateCreated = DateTime.Now; Optional dateModified = DateTime.Now; @@ -84,9 +87,11 @@ public class DirectoryTests public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() { // Arrange - Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsFailure); - Directory directory = directoryResult.Value; + Directory directory = _directoryFixture.Create( + path: "/valid/path", + name: "TestDirectory", + dateCreated: Optional.None(), + dateModified: Optional.None()); DateTime newDate = DateTime.Now; // Act @@ -101,10 +106,12 @@ public class DirectoryTests public void AddItem_WhenCalled_ShouldAddItemToCollection() { // Arrange - Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsFailure); - Directory directory = directoryResult.Value; - FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); + Directory directory = _directoryFixture.Create( + path: "/valid/path", + name: "TestDirectory", + dateCreated: Optional.None(), + dateModified: Optional.None()); + File item = _fileFixture.Create(path: "/mock/path", name: "MockItem"); // Act Result result = directory.AddItem(item); @@ -118,10 +125,12 @@ public class DirectoryTests public void RemoveItem_WhenCalledWithExistingItem_ShouldRemoveItemFromCollection() { // Arrange - Result directoryResult = Directory.Create("/valid/path", "TestDirectory", Optional.None(), Optional.None()); - Assert.False(directoryResult.IsFailure); - Directory directory = directoryResult.Value; - FileSystemItem item = new FileSystemItemFixture(FileSystemPathId.Create("/mock/path").Value, "MockItem", FileSystemItemType.File); + Directory directory = _directoryFixture.Create( + path: "/valid/path", + name: "TestDirectory", + dateCreated: Optional.None(), + dateModified: Optional.None()); + File item = _fileFixture.Create(path: "/mock/path", name: "MockItem"); directory.AddItem(item); // Act diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs index ea5c5af7..83f3e8f5 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/FileTests.cs @@ -3,6 +3,8 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System; using System.Diagnostics.CodeAnalysis; @@ -16,6 +18,9 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBound [ExcludeFromCodeCoverage] public class FileTests { + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly FileFixture _fileFixture = new(); + [Fact] public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() { @@ -61,9 +66,7 @@ public class FileTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - Result pathIdResult = FileSystemPathId.Create("/valid/path/file.txt"); - Assert.False(pathIdResult.IsFailure); - FileSystemPathId pathId = pathIdResult.Value; + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "/valid/path/file.txt"); string name = "file.txt"; Optional dateCreated = DateTime.Now; Optional dateModified = DateTime.Now; @@ -87,9 +90,12 @@ public class FileTests public void UpdateLastModified_WhenCalled_ShouldUpdateDateModified() { // Arrange - Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsFailure); - File file = fileResult.Value; + File file = _fileFixture.Create( + path: "/valid/path/file.txt", + name: "file.txt", + dateCreated: Optional.None(), + dateModified: Optional.None(), + size: 1024); DateTime newDate = DateTime.Now; // Act @@ -104,9 +110,12 @@ public class FileTests public void UpdateSize_WhenCalled_ShouldUpdateFileSize() { // Arrange - Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsFailure); - File file = fileResult.Value; + File file = _fileFixture.Create( + path: "/valid/path/file.txt", + name: "file.txt", + dateCreated: Optional.None(), + dateModified: Optional.None(), + size: 1024); long newSize = 2048; // Act @@ -121,9 +130,12 @@ public class FileTests public void Rename_WhenCalledWithValidName_ShouldUpdateFileName() { // Arrange - Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsFailure); - File file = fileResult.Value; + File file = _fileFixture.Create( + path: "/valid/path/file.txt", + name: "file.txt", + dateCreated: Optional.None(), + dateModified: Optional.None(), + size: 1024); string newName = "newfile.txt"; // Act @@ -138,9 +150,12 @@ public class FileTests public void Rename_WhenCalledWithEmptyName_ShouldReturnError() { // Arrange - Result fileResult = File.Create("/valid/path/file.txt", "file.txt", Optional.None(), Optional.None(), 1024); - Assert.False(fileResult.IsFailure); - File file = fileResult.Value; + File file = _fileFixture.Create( + path: "/valid/path/file.txt", + name: "file.txt", + dateCreated: Optional.None(), + dateModified: Optional.None(), + size: 1024); string emptyName = ""; // Act diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs index 5a75102c..338a2fc9 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/UnixRootItemTests.cs @@ -3,6 +3,7 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -16,6 +17,8 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBound [ExcludeFromCodeCoverage] public class UnixRootItemTests { + private readonly UnixRootItemFixture _unixRootItemFixture = new(); + [Fact] public void Create_WhenCalledWithDefaultStatus_ShouldReturnSuccessfulResult() { @@ -55,9 +58,7 @@ public class UnixRootItemTests public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() { // Arrange - Result createResult = UnixRootItem.Create(); - Assert.False(createResult.IsFailure); - UnixRootItem unixRootItem = createResult.Value; + UnixRootItem unixRootItem = _unixRootItemFixture.Create(); // Act IReadOnlyCollection items = unixRootItem.Items; @@ -71,9 +72,7 @@ public class UnixRootItemTests public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() { // Arrange - Result createResult = UnixRootItem.Create(); - Assert.False(createResult.IsFailure); - UnixRootItem unixRootItem = createResult.Value; + UnixRootItem unixRootItem = _unixRootItemFixture.Create(); FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; // Act @@ -88,9 +87,7 @@ public class UnixRootItemTests public void SetParent_WhenCalledWithNullParent_ShouldReturnError() { // Arrange - Result createResult = UnixRootItem.Create(); - Assert.False(createResult.IsFailure); - UnixRootItem unixRootItem = createResult.Value; + UnixRootItem unixRootItem = _unixRootItemFixture.Create(); // Act Result result = unixRootItem.SetParent(null!); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs index 30533f5e..aaa1c490 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Entities/WindowsRootItemTests.cs @@ -4,6 +4,8 @@ using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.FileSystem; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -17,6 +19,9 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.FileSystemManagementBound [ExcludeFromCodeCoverage] public class WindowsRootItemTests { + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly WindowsRootItemFixture _windowsRootItemFixture = new(); + [Fact] public void Create_WhenCalledWithValidParameters_ShouldReturnSuccessfulResult() { @@ -76,9 +81,7 @@ public class WindowsRootItemTests public void Create_WhenCalledWithFileSystemPathId_ShouldReturnSuccessfulResult() { // Arrange - Result pathIdResult = FileSystemPathId.Create("E:\\"); - Assert.False(pathIdResult.IsFailure); - FileSystemPathId pathId = pathIdResult.Value; + FileSystemPathId pathId = _fileSystemPathIdFixture.Create(path: "E:\\"); string name = "E:"; // Act @@ -97,9 +100,7 @@ public class WindowsRootItemTests public void Items_WhenAccessed_ShouldReturnEmptyReadOnlyCollection() { // Arrange - Result createResult = WindowsRootItem.Create("F:\\", "F:"); - Assert.False(createResult.IsFailure); - WindowsRootItem windowsRootItem = createResult.Value; + WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create(); // Act IReadOnlyCollection items = windowsRootItem.Items; @@ -113,9 +114,7 @@ public class WindowsRootItemTests public void SetStatus_WhenCalledWithNewStatus_ShouldUpdateStatus() { // Arrange - Result createResult = WindowsRootItem.Create("G:\\", "G:"); - Assert.False(createResult.IsFailure); - WindowsRootItem windowsRootItem = createResult.Value; + WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create(); FileSystemItemStatus newStatus = FileSystemItemStatus.Accessible; // Act @@ -130,10 +129,8 @@ public class WindowsRootItemTests public void SetParent_WhenCalledWithNullParent_ShouldReturnError() { // Arrange - Result createResult = WindowsRootItem.Create("H:\\", "H:"); - Assert.False(createResult.IsFailure); - WindowsRootItem windowsRootItem = createResult.Value; - + WindowsRootItem windowsRootItem = _windowsRootItemFixture.Create(); + // Act Result result = windowsRootItem.SetParent(null!); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs index a15c1e44..1d827fa3 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/DirectoryProviderServiceTests.cs @@ -792,7 +792,7 @@ public class DirectoryProviderServiceTests _mockFileSystem.Directory.Exists(destDir).Returns(true); // Act - _sut.MoveDirectory(FileSystemPathId.Create(sourceDir).Value, FileSystemPathId.Create(destDir).Value, overwrite); + _sut.MoveDirectory(_fileSystemPathIdFixture.Create(sourceDir), _fileSystemPathIdFixture.Create(destDir), overwrite); // Assert _mockFileSystem.Directory.Received(1).Delete(sourceDir); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs index 44056680..686ca380 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileProviderServiceTests.cs @@ -261,7 +261,7 @@ public class FileProviderServiceTests byte[] expectedContents = [1, 2, 3, 4, 5]; File.WriteAllBytes(tempFilePath, expectedContents); - FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); // We need to update the _fileSystem mock to use the real file system for this method @@ -303,7 +303,7 @@ public class FileProviderServiceTests string tempFilePath = Path.GetTempFileName(); try { - FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadContents).Returns(true); // Act @@ -328,7 +328,7 @@ public class FileProviderServiceTests try { File.WriteAllText(tempFilePath, "Test content"); - FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); DateTime expectedDateTime = File.GetLastWriteTime(tempFilePath); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); @@ -371,7 +371,7 @@ public class FileProviderServiceTests try { File.WriteAllText(tempFilePath, "Test content"); - FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); DateTime expectedDateTime = File.GetCreationTime(tempFilePath); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); @@ -415,7 +415,7 @@ public class FileProviderServiceTests { string content = "Test content"; File.WriteAllText(tempFilePath, content); - FileSystemPathId path = FileSystemPathId.Create(tempFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(tempFilePath); long expectedSize = new FileInfo(tempFilePath).Length; _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); @@ -455,7 +455,7 @@ public class FileProviderServiceTests { // Arrange string nonExistentFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - FileSystemPathId path = FileSystemPathId.Create(nonExistentFilePath).Value; + FileSystemPathId path = _fileSystemPathIdFixture.Create(nonExistentFilePath); _mockFileSystemPermissionsService.CanAccessPath(path, FileAccessMode.ReadProperties).Returns(true); _mockFileSystem.FileInfo.New(path.Path).Returns((IFileInfo)null!); @@ -875,7 +875,7 @@ public class FileProviderServiceTests _mockFileSystem.Path.Combine(parentPath, newName).Returns(newPath); // Mock successful creation of parent directory FileSystemPathId - Result parentDirectoryPathId = FileSystemPathId.Create(parentPath); + FileSystemPathId parentDirectoryPathId = _fileSystemPathIdFixture.Create(parentPath); _mockFileSystem.Path.GetDirectoryName(path.Path).Returns(parentPath); // Mock permissions: executable for the file, but not writable for the parent directory 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 3bebfe31..ba9710aa 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 @@ -444,7 +444,7 @@ public class PathServiceTests { // Arrange char[] originalInvalidChars = ['<', '>', ':', '"', '|', '?', '*']; - _mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(originalInvalidChars); + _mockPathStrategy.GetInvalidPathCharsForPlatform().Returns(_ => (char[])originalInvalidChars.Clone()); // Act char[] result = _sut.GetInvalidPathCharsForPlatform(); @@ -452,7 +452,7 @@ public class PathServiceTests // Assert char[] secondResult = _sut.GetInvalidPathCharsForPlatform(); - Assert.Equal(secondResult, originalInvalidChars); + Assert.Equal(originalInvalidChars, secondResult); _mockPathStrategy.Received(2).GetInvalidPathCharsForPlatform(); } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs new file mode 100644 index 00000000..5fc22425 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibraryDeletedDomainEventTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryDeletedDomainEventTests +{ + private readonly LibraryFixture _libraryFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + Library library = _libraryFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryDeletedDomainEvent domainEvent = new(id, library, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(library, domainEvent.Library); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs new file mode 100644 index 00000000..b00d2f18 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEventTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibrarySavedDomainEventTests +{ + private readonly LibraryFixture _libraryFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + Library library = _libraryFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibrarySavedDomainEvent domainEvent = new(id, library, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(library, domainEvent.Library); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} 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 new file mode 100644 index 00000000..82cede13 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -0,0 +1,228 @@ +#region ========================================================================= USING ===================================================================================== +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; +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.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryTests +{ + private readonly LibraryFixture _libraryFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateLibraryWithAllPropertiesSet() + { + // Arrange + UserId userId = _userIdFixture.Create(); + string title = "My Books"; + LibraryType libraryType = LibraryType.Book; + List contentLocations = ["C:/Media/Books", "D:/Books"]; + string coverImageSourcePath = "C:/Cover/cover.jpg"; + List scanIds = [_scanIdFixture.Create(), _scanIdFixture.Create()]; + + // Act + Result result = Library.Create( + userId, + title, + libraryType, + contentLocations, + coverImageSourcePath, + isEnabled: false, + isLocked: true, + downloadMetadataFromWeb: false, + shouldSaveMetadataInMediaDirectories: true, + shouldSkipUnchangedDirectoriesDuringScan: true, + scanIds); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(title, result.Value.Title); + Assert.Equal(libraryType, result.Value.LibraryType); + Assert.Equal(2, result.Value.ContentLocations.Count); + Assert.Equal(coverImageSourcePath, result.Value.CoverImage); + Assert.False(result.Value.IsEnabled); + Assert.True(result.Value.IsLocked); + Assert.False(result.Value.DownloadMetadataFromWeb); + Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories); + Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan); + Assert.Equal(scanIds, result.Value.ScanIds); + } + + [Fact] + public void Create_WhenCalledWithPreExistingId_ShouldCreateLibraryWithThatId() + { + // Arrange + Guid id = Guid.NewGuid(); + List scanIds = [_scanIdFixture.Create()]; + + // Act + Result result = Library.Create( + _libraryIdFixture.Create(id), + _userIdFixture.Create(), + "My Library", + LibraryType.Movie, + ["C:/Media"], + null, + isEnabled: true, + isLocked: false, + downloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + scanIds); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithContentLocations_ShouldCreateFileSystemPathIdForEachLocation() + { + // Act + Result result = Library.Create( + _userIdFixture.Create(), + "My Library", + LibraryType.Book, + ["C:/Media/Books", "D:/Books"], + null, + isEnabled: true, + isLocked: false, + downloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.ContentLocations.Count); + Assert.Contains(result.Value.ContentLocations, location => location.Path == "C:/Media/Books"); + Assert.Contains(result.Value.ContentLocations, location => location.Path == "D:/Books"); + } + + [Theory] + [InlineData(null)] // null content location + [InlineData("")] // empty content location + [InlineData(" ")] // whitespace content location + public void Create_WhenContentLocationIsInvalid_ShouldReturnError(string? contentLocation) + { + // Act + Result result = Library.Create( + _userIdFixture.Create(), + "My Library", + LibraryType.Book, + [contentLocation!], + null, + isEnabled: true, + isLocked: false, + downloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false, + []); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.FileSystemManagement.InvalidPath, result.FirstError); + } + + [Fact] + public void Save_WhenCalled_ShouldRaiseLibrarySavedDomainEvent() + { + // Arrange + Library library = _libraryFixture.Create(); + + // Act + library.Save(); + + // Assert + List domainEvents = library.GetDomainEvents(); + LibrarySavedDomainEvent savedEvent = Assert.IsType(Assert.Single(domainEvents)); + Assert.Equal(library, savedEvent.Library); + Assert.NotEqual(default, savedEvent.Id); + Assert.NotEqual(default, savedEvent.OccurredOnUtc); + } + + [Fact] + public void Delete_WhenCalled_ShouldRaiseLibraryDeletedDomainEvent() + { + // Arrange + Library library = _libraryFixture.Create(); + + // Act + Result result = library.Delete(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + List domainEvents = library.GetDomainEvents(); + LibraryDeletedDomainEvent deletedEvent = Assert.IsType(Assert.Single(domainEvents)); + Assert.Equal(library, deletedEvent.Library); + } + + [Fact] + public void Delete_WhenCalledAfterSave_ShouldClearPreviousEventsAndRaiseOnlyDeletedEvent() + { + // Arrange + Library library = _libraryFixture.Create(); + library.Save(); + + // Act + library.Delete(); + + // Assert + List domainEvents = library.GetDomainEvents(); + Assert.Single(domainEvents); + Assert.IsType(domainEvents[0]); + } + + [Fact] + public void Delete_WhenCalledMultipleTimes_ShouldRaiseOnlyOneDeletedEvent() + { + // Arrange + Library library = _libraryFixture.Create(); + + // Act + library.Delete(); + library.Delete(); + + // Assert + List domainEvents = library.GetDomainEvents(); + Assert.Single(domainEvents); + Assert.IsType(domainEvents[0]); + } + + [Fact] + public void SetInternalLibraryCoverImagePath_WhenCalled_ShouldUpdateCoverImage() + { + // Arrange + Library library = _libraryFixture.Create(); + string internalPath = "C:/Internal/Covers/cover.jpg"; + + // Act + library.SetInternalLibraryCoverImagePath(internalPath); + + // Assert + Assert.Equal(internalPath, library.CoverImage); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs new file mode 100644 index 00000000..ba23dd34 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryMediaItemDeletedDomainEventTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryMediaItemDeletedDomainEventTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + string path = "C:/Media/Books/old-book.pdf"; + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryMediaItemDeletedDomainEvent domainEvent = new(id, libraryId, compositeId, path, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); + Assert.Equal(path, domainEvent.Path); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsAssignableFrom(domainEvent); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs new file mode 100644 index 00000000..27b2b775 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanCancelledDomainEventTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanCancelledDomainEventTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScanId scanId = _scanIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanCancelledDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scanId, domainEvent.ScanId); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsAssignableFrom(domainEvent); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs new file mode 100644 index 00000000..8929c22f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFailedDomainEventTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFailedDomainEventTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void Constructor_WhenCalledWithErrorMessage_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + string errorMessage = "Scan failed unexpectedly."; + + // Act + LibraryScanFailedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc, errorMessage); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.Equal(errorMessage, domainEvent.ErrorMessage); + Assert.IsType(domainEvent, exactMatch: false); + } + + [Fact] + public void Constructor_WhenCalledWithoutErrorMessage_ShouldDefaultErrorMessageToNull() + { + // Act + LibraryScanFailedDomainEvent domainEvent = new( + Guid.NewGuid(), + _libraryIdFixture.Create(), + _mediaLibraryScanCompositeIdFixture.Create(), + DateTime.UtcNow); + + // Assert + Assert.Null(domainEvent.ErrorMessage); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs new file mode 100644 index 00000000..c411a16e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanFinishedDomainEventTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanFinishedDomainEventTests +{ + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanFinishedDomainEvent domainEvent = new(id, compositeId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs new file mode 100644 index 00000000..f22f9345 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanJobProgressChangedDomainEventTests.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanJobProgressChangedDomainEventTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanJobProgress progress = _mediaLibraryScanJobProgressFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanJobProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, progress, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); + Assert.Equal(progress, domainEvent.Progress); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs new file mode 100644 index 00000000..a96bac75 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanProgressChangedDomainEventTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanProgressChangedDomainEventTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanProgressChangedDomainEvent domainEvent = new(id, libraryId, compositeId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(compositeId, domainEvent.MediaLibraryScanCompositeId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs new file mode 100644 index 00000000..f45f64a5 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanQueuedDomainEventTests.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanQueuedDomainEventTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + ScanId scanId = _scanIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanQueuedDomainEvent domainEvent = new(id, scanId, libraryId, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scanId, domainEvent.ScanId); + Assert.Equal(libraryId, domainEvent.LibraryId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs new file mode 100644 index 00000000..e532b0ed --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Events/LibraryScanStartedDomainEventTests.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanStartedDomainEventTests +{ + private readonly LibraryScanFixture _libraryScanFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryScan scan = _libraryScanFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + LibraryScanStartedDomainEvent domainEvent = new(id, scan, occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(scan, domainEvent.LibraryScan); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs new file mode 100644 index 00000000..4c4eadb2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/LibraryScanTests.cs @@ -0,0 +1,292 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryScanTests +{ + private readonly LibraryScanFixture _libraryScanFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateScanWithPendingStatus() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + + // Act + Result result = LibraryScan.Create(libraryId, userId, []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status); + Assert.NotEqual(default, result.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndStatus_ShouldCreateScanWithThoseValues() + { + // Arrange + Guid id = Guid.NewGuid(); + LibraryId libraryId = _libraryIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + + // Act + Result result = LibraryScan.Create(_scanIdFixture.Create(id), libraryId, userId, LibraryScanJobStatus.Running, []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status); + } + + [Fact] + public void Create_WhenCalledTwice_ShouldGenerateDistinctIds() + { + // Act + Result firstResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []); + Result secondResult = LibraryScan.Create(_libraryIdFixture.Create(), _userIdFixture.Create(), []); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value); + } + + [Fact] + public void QueueScan_WhenNoActivePastScanExists_ShouldSucceedAndRaiseQueuedEvent() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + + // Act + Result result = scan.QueueScan(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Pending, scan.Status); + LibraryScanQueuedDomainEvent queuedEvent = Assert.IsType(Assert.Single(scan.GetDomainEvents())); + Assert.Equal(scan.Id, queuedEvent.ScanId); + Assert.Equal(scan.LibraryId, queuedEvent.LibraryId); + } + + [Fact] + public void QueueScan_WhenPastScanIsRunning_ShouldReturnError() + { + // Arrange + LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]); + + // Act + Result result = scan.QueueScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError); + Assert.Empty(scan.GetDomainEvents()); + } + + [Fact] + public void QueueScan_WhenPastScanIsPending_ShouldReturnError() + { + // Arrange + LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Pending); + LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]); + + // Act + Result result = scan.QueueScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError); + Assert.Empty(scan.GetDomainEvents()); + } + + [Fact] + public void StartScan_WhenPending_ShouldTransitionToRunningAndRaiseStartedEvent() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + + // Act + Result result = scan.StartScan(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Running, scan.Status); + LibraryScanStartedDomainEvent startedEvent = Assert.IsType(Assert.Single(scan.GetDomainEvents())); + Assert.Equal(scan, startedEvent.LibraryScan); + } + + [Theory] + [InlineData(LibraryScanJobStatus.Running)] // cannot start an already running scan + [InlineData(LibraryScanJobStatus.Completed)] // cannot start a completed scan + [InlineData(LibraryScanJobStatus.Canceled)] // cannot start a canceled scan + [InlineData(LibraryScanJobStatus.Failed)] // cannot start a failed scan + public void StartScan_WhenNotPending_ShouldReturnError(LibraryScanJobStatus status) + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: status); + + // Act + Result result = scan.StartScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError); + Assert.Equal(status, scan.Status); + Assert.Empty(scan.GetDomainEvents()); + } + + [Fact] + public void StartScan_WhenPastScanIsActive_ShouldReturnError() + { + // Arrange + LibraryScan pastScan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + LibraryScan scan = _libraryScanFixture.Create(pastScans: [pastScan]); + + // Act + Result result = scan.StartScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryAlreadyBeingScanned, result.FirstError); + Assert.Empty(scan.GetDomainEvents()); + } + + [Fact] + public void FinishScan_WhenRunning_ShouldTransitionToCompleted() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + + // Act + Result result = scan.FinishScan(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Completed, scan.Status); + } + + [Theory] + [InlineData(LibraryScanJobStatus.Pending)] // cannot complete a pending scan + [InlineData(LibraryScanJobStatus.Completed)] // cannot complete an already completed scan + [InlineData(LibraryScanJobStatus.Canceled)] // cannot complete a canceled scan + [InlineData(LibraryScanJobStatus.Failed)] // cannot complete a failed scan + public void FinishScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: status); + + // Act + Result result = scan.FinishScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CanOnlyCompleteRunningScans, result.FirstError); + Assert.Equal(status, scan.Status); + } + + [Fact] + public void CancelScan_WhenRunning_ShouldTransitionToCanceledAndRaiseCancelledEvent() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + + // Act + Result result = scan.CancelScan(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Canceled, scan.Status); + LibraryScanCancelledDomainEvent cancelledEvent = Assert.IsType(Assert.Single(scan.GetDomainEvents())); + Assert.Equal(scan.Id, cancelledEvent.ScanId); + Assert.Equal(scan.LibraryId, cancelledEvent.LibraryId); + } + + [Theory] + [InlineData(LibraryScanJobStatus.Pending)] // cannot cancel a pending scan + [InlineData(LibraryScanJobStatus.Completed)] // cannot cancel a completed scan + [InlineData(LibraryScanJobStatus.Canceled)] // cannot cancel an already canceled scan + [InlineData(LibraryScanJobStatus.Failed)] // cannot cancel a failed scan + public void CancelScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: status); + + // Act + Result result = scan.CancelScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CanOnlyCancelRunningScans, result.FirstError); + Assert.Equal(status, scan.Status); + Assert.Empty(scan.GetDomainEvents()); + } + + [Fact] + public void FailScan_WhenRunning_ShouldTransitionToFailed() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + + // Act + Result result = scan.FailScan(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Failed, scan.Status); + } + + [Theory] + [InlineData(LibraryScanJobStatus.Pending)] // cannot fail a pending scan + [InlineData(LibraryScanJobStatus.Completed)] // cannot fail a completed scan + [InlineData(LibraryScanJobStatus.Canceled)] // cannot fail a canceled scan + [InlineData(LibraryScanJobStatus.Failed)] // cannot fail an already failed scan + public void FailScan_WhenNotRunning_ShouldReturnError(LibraryScanJobStatus status) + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: status); + + // Act + Result result = scan.FailScan(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CanOnlyFailRunningScans, result.FirstError); + Assert.Equal(status, scan.Status); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactoryTests.cs new file mode 100644 index 00000000..b756c829 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobFactoryTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobFactoryTests +{ + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void CreateJob_WhenJobTypeIsRegistered_ShouldResolveJobAndSetLibraryId() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + IMediaLibraryScanJob expectedJob = Substitute.For(); + ServiceCollection services = new(); + services.AddSingleton(expectedJob); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScanJobFactory sut = new(serviceProvider); + + // Act + IMediaLibraryScanJob job = sut.CreateJob(libraryId); + + // Assert + Assert.Same(expectedJob, job); + Assert.Equal(libraryId, job.LibraryId); + } + + [Fact] + public void CreateJob_WhenJobTypeIsNotRegistered_ShouldThrowInvalidOperationException() + { + // Arrange + ServiceCollection services = new(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScanJobFactory sut = new(serviceProvider); + + // Act & Assert + Assert.Throws(() => sut.CreateJob(_libraryIdFixture.Create())); + } + + [Fact] + public void CreateJob_WhenServiceProviderReturnsNull_ShouldThrowInvalidOperationException() + { + // Arrange + MediaLibraryScanJobFactory sut = new(new NullServiceProvider()); + + // Act & Assert + InvalidOperationException exception = Assert.Throws(() => sut.CreateJob(_libraryIdFixture.Create())); + Assert.Contains("IMediaLibraryScanJob", exception.Message); + } + + /// + /// Test service provider that returns for every requested service. + /// + private sealed class NullServiceProvider : IServiceProvider + { + /// + /// Gets the service object of the specified type. + /// + /// The type of service to get. + /// . + public object? GetService(Type serviceType) + { + return null; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobTests.cs new file mode 100644 index 00000000..b5899e37 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Jobs/MediaLibraryScanJobTests.cs @@ -0,0 +1,175 @@ +#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.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.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + [Fact] + public void Status_WhenCreated_ShouldBePending() + { + // Act + TestMediaLibraryScanJob job = CreateJob(); + + // Assert + Assert.Equal(LibraryScanJobStatus.Pending, job.Status); + Assert.Empty(job.Children); + Assert.Empty(job.Parents); + } + + [Fact] + public void AddChild_WhenCalledWithNewJob_ShouldAddChild() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob child = CreateJob(); + + // Act + job.AddChild(child); + + // Assert + Assert.Single(job.Children); + Assert.Contains(child, job.Children); + } + + [Fact] + public void AddChild_WhenJobIsAlreadyChild_ShouldNotAddDuplicate() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob child = CreateJob(); + + // Act + job.AddChild(child); + job.AddChild(child); + + // Assert + Assert.Single(job.Children); + } + + [Fact] + public void AddChild_WhenJobIsParent_ShouldNotAddChild() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob parent = CreateJob(); + job.AddParent(parent); + + // Act + job.AddChild(parent); + + // Assert + Assert.Empty(job.Children); + Assert.Single(job.Parents); + } + + [Fact] + public void AddParent_WhenCalledWithNewJob_ShouldAddParent() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob parent = CreateJob(); + + // Act + job.AddParent(parent); + + // Assert + Assert.Single(job.Parents); + Assert.Contains(parent, job.Parents); + } + + [Fact] + public void AddParent_WhenJobIsAlreadyParent_ShouldNotAddDuplicate() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob parent = CreateJob(); + + // Act + job.AddParent(parent); + job.AddParent(parent); + + // Assert + Assert.Single(job.Parents); + } + + [Fact] + public void AddParent_WhenJobIsChild_ShouldNotAddParent() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + TestMediaLibraryScanJob child = CreateJob(); + job.AddChild(child); + + // Act + job.AddParent(child); + + // Assert + Assert.Single(job.Children); + Assert.Empty(job.Parents); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldCompleteWithoutChangingJobState() + { + // Arrange + TestMediaLibraryScanJob job = CreateJob(); + + // Act + await job.ExecuteAsync(Guid.NewGuid(), "input", CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Pending, job.Status); + Assert.Empty(job.Children); + Assert.Empty(job.Parents); + } + + private TestMediaLibraryScanJob CreateJob() + { + return new TestMediaLibraryScanJob + { + ScanId = _scanIdFixture.Create(), + UserId = _userIdFixture.Create(), + LibraryId = _libraryIdFixture.Create() + }; + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestMediaLibraryScanJob : MediaLibraryScanJob + { + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter. + /// The unique identifier of the media library scan job. + /// The input data to be processed. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public override Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} 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 new file mode 100644 index 00000000..fd417778 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningServiceTests.cs @@ -0,0 +1,205 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; +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; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; +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.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +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; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanningServiceTests +{ + private readonly IMediaLibrariesScanQueue _mockScanQueue; + private readonly IMediaLibraryScannerFactory _mockScannerFactory; + private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; + private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MediaLibraryScanningService _sut; + private readonly LibraryScanFixture _libraryScanFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly Channel _channel; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanningServiceTests() + { + _channel = Channel.CreateUnbounded(); + _mockScanQueue = Substitute.For(); + _mockScanQueue.Writer.Returns(_channel.Writer); + _mockScanQueue.Reader.Returns(_channel.Reader); + _mockScannerFactory = Substitute.For(); + _mockCancellationTracker = Substitute.For(); + _mockCancellationTracker.GetTokenForScan(Arg.Any()).Returns(CancellationToken.None); + _mockProgressTracker = Substitute.For(); + _mockProgressTracker.InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Result.Created); + _mockDomainEventPublisher = Substitute.For(); + _sut = new MediaLibraryScanningService(_mockScanQueue, _mockScannerFactory, _mockCancellationTracker, _mockProgressTracker, _mockDomainEventPublisher); + } + + [Fact] + public async Task StartScanAsync_WhenScanStartsSuccessfully_ShouldPublishEventsAndEnqueueJobs() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + IMediaLibraryScanJob job = CreateJob(children: []); + IMediaTypeScanner scanner = CreateScanner([job]); + + // Act + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + Assert.Equal(LibraryScanJobStatus.Running, scan.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Any(), Arg.Any()); + _mockCancellationTracker.Received(1).RegisterScan(Arg.Is(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId)); + _mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any(), totalJobs: 1); + Assert.Equal(scan.Id, job.ScanId); + Assert.Equal(scan.UserId, job.UserId); + Assert.True(_channel.Reader.TryRead(out IMediaLibraryScanJob? enqueuedJob)); + Assert.Same(job, enqueuedJob); + Assert.False(_channel.Reader.TryRead(out _)); + } + + [Fact] + public async Task StartScanAsync_WhenScanCannotStart_ShouldReturnErrorAndNotEnqueueJobs() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(status: LibraryScanJobStatus.Running); + + // Act + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Lumina.Domain.Common.Errors.Errors.LibraryScanning.CanOnlyStartPendingScans, result.FirstError); + await _mockDomainEventPublisher.DidNotReceive().PublishAsync(Arg.Any(), Arg.Any()); + _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); + Assert.False(_channel.Reader.TryRead(out _)); + } + + [Fact] + public async Task StartScanAsync_WhenScannerThrowsNotImplementedException_ShouldSucceedWithoutEnqueuingJobs() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + IMediaTypeScanner scanner = Substitute.For(); + scanner.CreateScanJobsForLibrary(Arg.Any(), 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); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + _mockProgressTracker.DidNotReceive().InitializeScanProgress(Arg.Any(), Arg.Any(), Arg.Any()); + Assert.False(_channel.Reader.TryRead(out _)); + } + + [Fact] + public async Task StartScanAsync_WhenJobGraphHasSharedChild_ShouldCountOnlyUniqueJobs() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + IMediaLibraryScanJob sharedChild = CreateJob(children: []); + IMediaLibraryScanJob firstRoot = CreateJob(children: [sharedChild]); + IMediaLibraryScanJob secondRoot = CreateJob(children: [sharedChild]); + IMediaTypeScanner scanner = CreateScanner([firstRoot, secondRoot]); + + // Act + Result result = await _sut.StartScanAsync(scan, LibraryType.Book, downloadMetadataFromWeb: false, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockProgressTracker.Received(1).InitializeScanProgress(scan.LibraryId, Arg.Any(), totalJobs: 3); + Assert.Equal(2, CountEnqueuedJobs()); + } + + [Fact] + public void CancelScan_WhenCalled_ShouldCancelScanInTracker() + { + // Arrange + LibraryScan scan = _libraryScanFixture.Create(); + + // Act + Result result = _sut.CancelScan(scan); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Success, result.Value); + _mockCancellationTracker.Received(1).CancelScan(Arg.Is(compositeId => compositeId.ScanId == scan.Id && compositeId.UserId == scan.UserId)); + } + + [Fact] + public void SetScanPropertiesForJobChain_WhenCalled_ShouldSetScanPropertiesRecursively() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + IMediaLibraryScanJob leafJob = CreateJob(children: []); + IMediaLibraryScanJob middleJob = CreateJob(children: [leafJob]); + IMediaLibraryScanJob rootJob = CreateJob(children: [middleJob]); + + // Act + MediaLibraryScanningService.SetScanPropertiesForJobChain(rootJob, scanId, userId); + + // Assert + Assert.Equal(scanId, rootJob.ScanId); + Assert.Equal(userId, rootJob.UserId); + Assert.Equal(scanId, middleJob.ScanId); + Assert.Equal(userId, middleJob.UserId); + Assert.Equal(scanId, leafJob.ScanId); + Assert.Equal(userId, leafJob.UserId); + } + + private IMediaTypeScanner CreateScanner(List jobs) + { + IMediaTypeScanner scanner = Substitute.For(); + scanner.CreateScanJobsForLibrary(Arg.Any(), Arg.Any()).Returns(jobs); + _mockScannerFactory.CreateLibraryScanner(LibraryType.Book).Returns(scanner); + return scanner; + } + + private static IMediaLibraryScanJob CreateJob(List children) + { + IMediaLibraryScanJob job = Substitute.For(); + job.Children.Returns(children); + return job; + } + + private int CountEnqueuedJobs() + { + int count = 0; + while (_channel.Reader.TryRead(out _)) + count++; + return count; + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs new file mode 100644 index 00000000..2f189b6b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Progress/MediaLibrariesScanProgressTrackerTests.cs @@ -0,0 +1,197 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibrariesScanProgressTrackerTests +{ + private readonly MediaLibrariesScanProgressTracker _sut = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + + [Fact] + public void InitializeScanProgress_WhenCalled_ShouldCreateProgressWithZeroCompletedJobs() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + Result result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 5); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.Equal(0, progressResult.Value.CompletedJobs); + Assert.Equal(5, progressResult.Value.TotalJobs); + Assert.Equal(LibraryScanJobStatus.Pending, progressResult.Value.Status); + Assert.True(progressResult.Value.CurrentJobProgress.HasValue); + Assert.Equal("Initializing", progressResult.Value.CurrentJobProgress.Value.CurrentOperation); + } + + [Fact] + public void InitializeScanProgress_WhenTotalJobsIsNotPositive_ShouldReturnError() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + Result result = _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 0); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError); + } + + [Fact] + public void UpdateScanProgress_WhenScanExists_ShouldIncrementCompletedJobs() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2); + + // Act + Result result = _sut.UpdateScanProgress(libraryId, compositeId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.Equal(1, progressResult.Value.CompletedJobs); + Assert.Equal(LibraryScanJobStatus.Running, progressResult.Value.Status); + } + + [Fact] + public void UpdateScanProgress_WhenLastJobIsCompleted_ShouldSetStatusCompleted() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 1); + + // Act + Result result = _sut.UpdateScanProgress(libraryId, compositeId); + + // Assert + Assert.False(result.IsFailure); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.Equal(1, progressResult.Value.CompletedJobs); + Assert.Equal(LibraryScanJobStatus.Completed, progressResult.Value.Status); + Assert.Equal(100, progressResult.Value.OverallProgressPercentage); + } + + [Fact] + public void UpdateScanJobProgress_WhenScanExists_ShouldUpdateCurrentJobProgress() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 2); + MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 3, totalItems: 10, currentOperation: "Hashing files"); + + // Act + Result result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Result progressResult = _sut.GetScanProgress(compositeId); + Assert.False(progressResult.IsFailure); + Assert.True(progressResult.Value.CurrentJobProgress.HasValue); + Assert.Equal(3, progressResult.Value.CurrentJobProgress.Value.CompletedItems); + Assert.Equal("Hashing files", progressResult.Value.CurrentJobProgress.Value.CurrentOperation); + } + + [Fact] + public void UpdateScanJobProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 1, totalItems: 10, currentOperation: "Hashing files"); + + // Act + Result result = _sut.UpdateScanJobProgress(libraryId, compositeId, jobProgress); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError); + } + + [Fact] + public void GetScanProgress_WhenScanExists_ShouldReturnProgress() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3); + + // Act + Result result = _sut.GetScanProgress(compositeId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(compositeId.ScanId, result.Value.ScanId); + Assert.Equal(compositeId.UserId, result.Value.UserId); + Assert.Equal(libraryId, result.Value.LibraryId); + } + + [Fact] + public void GetScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError() + { + // Act + Result result = _sut.GetScanProgress(_mediaLibraryScanCompositeIdFixture.Create()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError); + } + + [Fact] + public void RemoveScanProgress_WhenScanExists_ShouldRemoveAndReturnProgress() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _sut.InitializeScanProgress(libraryId, compositeId, totalJobs: 3); + + // Act + Result result = _sut.RemoveScanProgress(compositeId); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(compositeId.ScanId, result.Value.ScanId); + Assert.True(_sut.GetScanProgress(compositeId).IsFailure); + } + + [Fact] + public void RemoveScanProgress_WhenScanDoesNotExist_ShouldReturnNotFoundError() + { + // Act + Result result = _sut.RemoveScanProgress(_mediaLibraryScanCompositeIdFixture.Create()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.LibraryScanNotFound, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs new file mode 100644 index 00000000..33356182 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/MediaLibraryScannerFactoryTests.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScannerFactoryTests +{ + [Fact] + public void CreateLibraryScanner_WhenLibraryTypeIsBook_ShouldReturnBookLibraryTypeScanner() + { + // Arrange + IBookLibraryTypeScanner expectedScanner = Substitute.For(); + ServiceCollection services = new(); + services.AddSingleton(expectedScanner); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScannerFactory sut = new(serviceProvider); + + // Act + IMediaTypeScanner scanner = sut.CreateLibraryScanner(LibraryType.Book); + + // Assert + Assert.Same(expectedScanner, scanner); + } + + [Theory] + [InlineData(LibraryType.EBook)] // eBook scanner is not implemented + [InlineData(LibraryType.Movie)] // movie scanner is not implemented + [InlineData(LibraryType.Music)] // music scanner is not implemented + [InlineData(LibraryType.Photo)] // photo scanner is not implemented + public void CreateLibraryScanner_WhenLibraryTypeIsNotImplemented_ShouldThrowNotImplementedException(LibraryType libraryType) + { + // Arrange + ServiceCollection services = new(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScannerFactory sut = new(serviceProvider); + + // Act & Assert + Assert.Throws(() => sut.CreateLibraryScanner(libraryType)); + } + + [Fact] + public void CreateLibraryScanner_WhenLibraryTypeIsUnknown_ShouldThrowArgumentOutOfRangeException() + { + // Arrange + ServiceCollection services = new(); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + MediaLibraryScannerFactory sut = new(serviceProvider); + + // Act & Assert + Assert.Throws(() => sut.CreateLibraryScanner((LibraryType)999)); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdTests.cs new file mode 100644 index 00000000..a537130a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanCompositeIdTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanCompositeIdTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void Create_WhenCalledWithScanIdAndUserId_ShouldCreateCompositeIdWithThoseValues() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + + // Act + MediaLibraryScanCompositeId compositeId = MediaLibraryScanCompositeId.Create(scanId, userId); + + // Assert + Assert.Equal(scanId, compositeId.ScanId); + Assert.Equal(userId, compositeId.UserId); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + + // Act + MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId); + MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId); + + // Assert + Assert.Equal(firstId, secondId); + } + + [Fact] + public void Equals_WithDifferentScanId_ShouldReturnFalse() + { + // Arrange + UserId userId = _userIdFixture.Create(); + + // Act + MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId); + MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(userId: userId); + + // Assert + Assert.NotEqual(firstId, secondId); + } + + [Fact] + public void GetHashCode_WithSameValues_ShouldReturnSameHashCode() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + + // Act + MediaLibraryScanCompositeId firstId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId); + MediaLibraryScanCompositeId secondId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId); + + // Assert + Assert.Equal(firstId.GetHashCode(), secondId.GetHashCode()); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnFormattedString() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(scanId: scanId, userId: userId); + + // Act + string result = compositeId.ToString(); + + // Assert + Assert.Equal($"{scanId}-{userId}", result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressTests.cs new file mode 100644 index 00000000..e9abdbf2 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanJobProgressTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProgressTests +{ + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateJobProgressWithExpectedValues() + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: 2, totalItems: 10, "Scanning files"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.CompletedItems); + Assert.Equal(10, result.Value.TotalItems); + Assert.Equal("Scanning files", result.Value.CurrentOperation); + Assert.Equal(20, result.Value.ProgressPercentage); + } + + [Fact] + public void Create_WhenTotalItemsIsZero_ShouldCreateJobProgressWithZeroPercentage() + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: 0, "Scanning files"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0, result.Value.ProgressPercentage); + } + + [Fact] + public void Create_WhenTotalItemsIsNegative_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: 0, totalItems: -1, "Scanning files"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.TotalScanJobItemsCountMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenCompletedItemsIsNegative_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: -1, totalItems: 10, "Scanning files"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenCompletedItemsExceedsTotalItems_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: 11, totalItems: 10, "Scanning files"); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobItemsCountCantExceedTotalScanJobItemsCount, result.FirstError); + } + + [Theory] + [InlineData(null)] // null current operation + [InlineData("")] // empty current operation + [InlineData(" ")] // whitespace current operation + public void Create_WhenCurrentOperationIsEmpty_ShouldReturnError(string? currentOperation) + { + // Act + Result result = MediaLibraryScanJobProgress.Create(completedItems: 1, totalItems: 10, currentOperation!); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.ScanJobCurrentOperationCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files"); + MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files"); + + // Act + bool result = firstProgress.Equals(secondProgress); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentCurrentOperation_ShouldReturnFalse() + { + // Arrange + MediaLibraryScanJobProgress firstProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files"); + MediaLibraryScanJobProgress secondProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Hashing files"); + + // Act + bool result = firstProgress.Equals(secondProgress); + + // Assert + Assert.False(result); + } + + [Fact] + public void ToString_WhenCalled_ShouldReturnFormattedString() + { + // Arrange + MediaLibraryScanJobProgress jobProgress = _mediaLibraryScanJobProgressFixture.Create(completedItems: 2, totalItems: 10, currentOperation: "Scanning files"); + + // Act + string result = jobProgress.ToString(); + + // Assert + Assert.Equal("CompletedItems: 2; TotalItems: 10; CurrentOperation: Scanning files", result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs new file mode 100644 index 00000000..d271dab9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/MediaLibraryScanProgressTests.cs @@ -0,0 +1,200 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.MediaLibrary; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProgressTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanJobProgressFixture _mediaLibraryScanJobProgressFixture = new(); + private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateProgressWithExpectedValues() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + Optional currentJobProgress = Optional.Some(_mediaLibraryScanJobProgressFixture.Create()); + + // Act + Result result = MediaLibraryScanProgress.Create(scanId, userId, libraryId, completedJobs: 2, totalJobs: 5, LibraryScanJobStatus.Running, currentJobProgress); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(scanId, result.Value.ScanId); + Assert.Equal(userId, result.Value.UserId); + Assert.Equal(libraryId, result.Value.LibraryId); + Assert.Equal(2, result.Value.CompletedJobs); + Assert.Equal(5, result.Value.TotalJobs); + Assert.Equal(LibraryScanJobStatus.Running, result.Value.Status); + Assert.True(result.Value.CurrentJobProgress.HasValue); + Assert.Equal(40, result.Value.OverallProgressPercentage); + } + + [Fact] + public void Create_WhenCalledWithDefaults_ShouldUsePendingStatusAndNoCurrentJobProgress() + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: 0, + totalJobs: 1, + LibraryScanJobStatus.Pending, + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(LibraryScanJobStatus.Pending, result.Value.Status); + Assert.False(result.Value.CurrentJobProgress.HasValue); + } + + [Theory] + [InlineData(0)] // total jobs must be positive + [InlineData(-1)] // total jobs must be positive + public void Create_WhenTotalJobsIsNotPositive_ShouldReturnError(int totalJobs) + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: 0, + totalJobs: totalJobs, + LibraryScanJobStatus.Pending, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.TotalScanJobsCountMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenCompletedJobsIsNegative_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: -1, + totalJobs: 5, + LibraryScanJobStatus.Pending, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenCompletedJobsExceedsTotalJobs_ShouldReturnError() + { + // Act + Result result = MediaLibraryScanProgress.Create( + _scanIdFixture.Create(), + _userIdFixture.Create(), + _libraryIdFixture.Create(), + completedJobs: 6, + totalJobs: 5, + LibraryScanJobStatus.Pending, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.LibraryScanning.CompletedScanJobsCountCantExceedTotalScanJobsCount, result.FirstError); + } + + [Fact] + public void OverallProgressPercentage_WhenNoJobsCompleted_ShouldReturnZero() + { + // Arrange + MediaLibraryScanProgress scanProgress = _mediaLibraryScanProgressFixture.Create(completedJobs: 0, totalJobs: 5); + + // Act + decimal result = scanProgress.OverallProgressPercentage; + + // Assert + Assert.Equal(0, result); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + + // Act + MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create( + scanId: scanId, + userId: userId, + libraryId: libraryId, + completedJobs: 2, + totalJobs: 5, + status: LibraryScanJobStatus.Running, + currentJobProgress: Optional.None()); + MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create( + scanId: scanId, + userId: userId, + libraryId: libraryId, + completedJobs: 2, + totalJobs: 5, + status: LibraryScanJobStatus.Running, + currentJobProgress: Optional.None()); + + // Assert + Assert.Equal(firstResult, secondResult); + } + + [Fact] + public void Equals_WithDifferentCompletedJobs_ShouldReturnFalse() + { + // Arrange + ScanId scanId = _scanIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + LibraryId libraryId = _libraryIdFixture.Create(); + + // Act + MediaLibraryScanProgress firstResult = _mediaLibraryScanProgressFixture.Create( + scanId: scanId, + userId: userId, + libraryId: libraryId, + completedJobs: 2, + totalJobs: 5, + status: LibraryScanJobStatus.Running, + currentJobProgress: Optional.None()); + MediaLibraryScanProgress secondResult = _mediaLibraryScanProgressFixture.Create( + scanId: scanId, + userId: userId, + libraryId: libraryId, + completedJobs: 3, + totalJobs: 5, + status: LibraryScanJobStatus.Running, + currentJobProgress: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdTests.cs new file mode 100644 index 00000000..3801a498 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/ValueObjects/ScanIdTests.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanIdTests +{ + private readonly ScanIdFixture _scanIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + ScanId scanId = ScanId.CreateUnique(); + + // Assert + Assert.NotNull(scanId); + Assert.NotEqual(default, scanId.Value); + } + + [Fact] + public void CreateUnique_WhenCalledTwice_ShouldReturnDistinctIds() + { + // Act + ScanId firstId = ScanId.CreateUnique(); + ScanId secondId = ScanId.CreateUnique(); + + // Assert + Assert.NotEqual(firstId.Value, secondId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + ScanId scanId = ScanId.Create(value); + + // Assert + Assert.Equal(value, scanId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + ScanId firstId = _scanIdFixture.Create(value); + ScanId secondId = _scanIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + ScanId firstId = _scanIdFixture.Create(); + ScanId secondId = _scanIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs new file mode 100644 index 00000000..a27e416b --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/MediaContributorTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorTests +{ + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + private readonly MediaContributorNameFixture _mediaContributorNameFixture = new(); + private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new(); + + [Fact] + public void Create_WhenCalledWithPreExistingIdAndValues_ShouldCreateContributor() + { + // Arrange + MediaContributorId id = _mediaContributorIdFixture.Create(); + MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.Some("Jane Doe Smith")); + MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + Optional dateOfBirth = Optional.Some(new DateOnly(1980, 1, 1)); + Optional dateOfDeath = Optional.None(); + + // Act + Result result = MediaContributor.Create(id, name, role, dateOfBirth, dateOfDeath); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id); + Assert.Equal(name, result.Value.Name); + Assert.Equal(role, result.Value.Role); + Assert.True(result.Value.DateOfBirth.HasValue); + Assert.Equal(new DateOnly(1980, 1, 1), result.Value.DateOfBirth.Value); + Assert.False(result.Value.DateOfDeath.HasValue); + Assert.False(result.Value.Biography.HasValue); + } + + [Fact] + public void Create_WhenCalledWithOptionalValuesAbsent_ShouldCreateContributorWithoutThem() + { + // Arrange + MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); + MediaContributorRole role = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + + // Act + Result result = MediaContributor.Create(_mediaContributorIdFixture.Create(), name, role, Optional.None(), Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.DateOfBirth.HasValue); + Assert.False(result.Value.DateOfDeath.HasValue); + } + + [Fact] + public void Create_WhenCalledWithoutId_ShouldThrowNotImplementedException() + { + // Arrange + MediaContributorName name = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); + + // Act & Assert + Assert.Throws(() => MediaContributor.Create(name)); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdTests.cs new file mode 100644 index 00000000..d5103d9e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorIdTests +{ + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + MediaContributorId contributorId = MediaContributorId.CreateUnique(); + + // Assert + Assert.NotNull(contributorId); + Assert.NotEqual(default, contributorId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + MediaContributorId contributorId = MediaContributorId.Create(value); + + // Assert + Assert.Equal(value, contributorId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + MediaContributorId firstId = _mediaContributorIdFixture.Create(value); + MediaContributorId secondId = _mediaContributorIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + MediaContributorId firstId = _mediaContributorIdFixture.Create(); + MediaContributorId secondId = _mediaContributorIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs new file mode 100644 index 00000000..5ff0c4d6 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorNameTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorNameTests +{ + private readonly MediaContributorNameFixture _mediaContributorNameFixture = new(); + + [Fact] + public void Create_WhenCalledWithDisplayNameAndLegalName_ShouldCreateName() + { + // Act + Result result = MediaContributorName.Create("Jane Doe", Optional.Some("Jane Doe Smith")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Jane Doe", result.Value.DisplayName); + Assert.True(result.Value.LegalName.HasValue); + Assert.Equal("Jane Doe Smith", result.Value.LegalName.Value); + } + + [Fact] + public void Create_WhenCalledWithoutLegalName_ShouldCreateNameWithoutLegalName() + { + // Act + Result result = MediaContributorName.Create("Jane Doe", Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Jane Doe", result.Value.DisplayName); + Assert.False(result.Value.LegalName.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MediaContributorName firstName = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); + MediaContributorName secondName = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); + + // Act + bool result = firstName.Equals(secondName); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentDisplayName_ShouldReturnFalse() + { + // Arrange + MediaContributorName firstName = _mediaContributorNameFixture.Create(displayName: "Jane Doe", legalName: Optional.None()); + MediaContributorName secondName = _mediaContributorNameFixture.Create(displayName: "John Smith", legalName: Optional.None()); + + // Act + bool result = firstName.Equals(secondName); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs new file mode 100644 index 00000000..f97b010f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/MediaContributorBoundedContext/MediaContributorAggregate/ValueObjects/MediaContributorRoleTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaContributorRoleTests +{ + private readonly MediaContributorRoleFixture _mediaContributorRoleFixture = new(); + + [Fact] + public void Create_WhenCalledWithNameAndCategory_ShouldCreateRole() + { + // Act + MediaContributorRole role = MediaContributorRole.Create("Actor", "Crew"); + + // Assert + Assert.Equal("Actor", role.Name); + Assert.Equal("Crew", role.Category); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + + // Act + bool result = firstRole.Equals(secondRole); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentName_ShouldReturnFalse() + { + // Arrange + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Director", category: "Crew"); + + // Act + bool result = firstRole.Equals(secondRole); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentCategory_ShouldReturnFalse() + { + // Arrange + MediaContributorRole firstRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Crew"); + MediaContributorRole secondRole = _mediaContributorRoleFixture.Create(name: "Actor", category: "Voice"); + + // Act + bool result = firstRole.Equals(secondRole); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserTests.cs new file mode 100644 index 00000000..46b5d082 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserAggregate/UserTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UserTests +{ + private readonly UserIdFixture _userIdFixture = new(); + private readonly UserFixture _userFixture = new(); + + [Fact] + public void Create_WhenCalledWithUsername_ShouldCreateUserWithGeneratedId() + { + // Act + Result result = User.Create("testUser"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("testUser", result.Value.Username); + Assert.NotEqual(default, result.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithPreExistingId_ShouldCreateUserWithThatId() + { + // Arrange + Guid id = Guid.NewGuid(); + + // Act + Result result = User.Create(_userIdFixture.Create(id), "testUser"); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + Assert.Equal("testUser", result.Value.Username); + } + + [Fact] + public void Create_WhenCalledTwice_ShouldGenerateDistinctIds() + { + // Act + Result firstResult = User.Create("firstUser"); + Result secondResult = User.Create("secondUser"); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value.Id.Value, secondResult.Value.Id.Value); + } + + [Fact] + public void Equals_WithSameId_ShouldReturnTrue() + { + // Arrange + Guid id = Guid.NewGuid(); + User firstUser = _userFixture.Create(id: id); + User secondUser = _userFixture.Create(id: id); + + // Act + bool result = firstUser.Equals(secondUser); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentId_ShouldReturnFalse() + { + // Arrange + User firstUser = _userFixture.Create(username: "firstUser"); + User secondUser = _userFixture.Create(username: "secondUser"); + + // Act + bool result = firstUser.Equals(secondUser); + + // Assert + Assert.False(result); + } +} 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 7212fa13..8b0460c0 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 @@ -3,6 +3,8 @@ using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; 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 @@ -15,11 +17,14 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.UserManagementBoundedCont [ExcludeFromCodeCoverage] public class UserSettingsTests { + private readonly UserIdFixture _userIdFixture = new(); + private readonly UserSettingsFixture _userSettingsFixture = new(); + [Fact] public void Create_WhenCalledWithoutValues_ShouldCreateSettingsWithDefaultValues() { // Arrange - UserId userId = UserId.CreateUnique(); + UserId userId = _userIdFixture.Create(); // Act Result result = UserSettings.Create(userId); @@ -64,7 +69,7 @@ public class UserSettingsTests public void Create_WhenCalledWithValidValues_ShouldCreateSettings() { // Arrange - UserId userId = UserId.CreateUnique(); + UserId userId = _userIdFixture.Create(); // Act Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true); @@ -81,7 +86,7 @@ public class UserSettingsTests public void Create_WhenCalledWithValidValues_ShouldGenerateDistinctSettingsIdFromUserId() { // Arrange - UserId userId = UserId.CreateUnique(); + UserId userId = _userIdFixture.Create(); // Act Result result = UserSettings.Create(userId); @@ -97,7 +102,7 @@ public class UserSettingsTests public void Create_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) { // Arrange - UserId userId = UserId.CreateUnique(); + UserId userId = _userIdFixture.Create(); // Act Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); @@ -111,16 +116,16 @@ public class UserSettingsTests public void UpdateSettings_WhenCalledWithValidValues_ShouldUpdateSettings() { // Arrange - Result createResult = UserSettings.Create(UserId.CreateUnique()); + UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = createResult.Value.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true); // Assert Assert.False(result.IsFailure); - Assert.False(createResult.Value.IsPaginationEnabled); - Assert.Equal(12, createResult.Value.ItemsPerPage); - Assert.True(createResult.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(userSettings.IsPaginationEnabled); + Assert.Equal(12, userSettings.ItemsPerPage); + Assert.True(userSettings.IgnoreThePrefixForAlphaPicker); } [Theory] @@ -129,10 +134,10 @@ public class UserSettingsTests public void UpdateSettings_WhenItemsPerPageIsNotPositive_ShouldReturnError(int itemsPerPage) { // Arrange - Result createResult = UserSettings.Create(UserId.CreateUnique()); + UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = createResult.Value.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); + Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs new file mode 100644 index 00000000..c62d157f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/MovieTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovieTests +{ + private readonly VideoMetadataFixture _videoMetadataFixture = new(); + private readonly MovieIdFixture _movieIdFixture = new(); + private readonly MediaContributorIdFixture _mediaContributorIdFixture = new(); + private readonly MovieFixture _movieFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateMovieWithGeneratedId() + { + // Arrange + VideoMetadata metadata = _videoMetadataFixture.Create(); + List contributors = [_mediaContributorIdFixture.Create()]; + List ratings = []; + + // Act + Result result = Movie.Create(metadata, contributors, ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(metadata, result.Value.Metadata); + Assert.Single(result.Value.Contributors); + Assert.Empty(result.Value.Ratings); + Assert.NotEqual(default, result.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithPreExistingId_ShouldCreateMovieWithThatId() + { + // Arrange + Guid id = Guid.NewGuid(); + VideoMetadata metadata = _videoMetadataFixture.Create(); + List contributors = []; + List ratings = []; + + // Act + Result result = Movie.Create(_movieIdFixture.Create(id), metadata, contributors, ratings); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + Assert.Equal(metadata, result.Value.Metadata); + } + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + MovieId id = _movieIdFixture.Create(); + VideoMetadata metadata = _videoMetadataFixture.Create(); + List contributors = [_mediaContributorIdFixture.Create(), _mediaContributorIdFixture.Create()]; + List ratings = [CreateRating(4.5m)]; + + // Act + Movie movie = new(id, metadata, contributors, ratings); + + // Assert + Assert.Equal(id, movie.Id); + Assert.Equal(metadata, movie.Metadata); + Assert.Equal(2, movie.Contributors.Count); + Assert.Single(movie.Ratings); + } + + [Fact] + public void Equals_WithSameId_ShouldReturnTrue() + { + // Arrange + Guid id = Guid.NewGuid(); + Movie firstMovie = _movieFixture.Create(id: _movieIdFixture.Create(id)); + Movie secondMovie = _movieFixture.Create(id: _movieIdFixture.Create(id)); + + // Act + bool result = firstMovie.Equals(secondMovie); + + // Assert + Assert.True(result); + } + + private static Rating CreateRating(decimal value) + { + return new TestRating(value, 10); + } + + /// + /// Concrete test implementation of the abstract class. + /// + private sealed class TestRating : Rating + { + /// + /// Initializes a new instance of the class. + /// + /// The numeric value of the rating. + /// The maximum possible rating value. + public TestRating(decimal value, decimal maxValue) : base(value, maxValue, Optional.None()) + { + } + + /// + /// Gets the list of items that define equality of the object. + /// + /// A list of items defining the equality. + public override IEnumerable GetEqualityComponents() + { + yield return Value; + yield return MaxValue; + yield return VoteCount; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryServiceTests.cs new file mode 100644 index 00000000..b4b1789f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/Services/MovieLibraryServiceTests.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovieLibraryServiceTests +{ + [Fact] + public void Movies_WhenAccessed_ShouldThrowNotImplementedException() + { + // Arrange + MovieLibraryService sut = new(); + + // Act & Assert + Assert.Throws(() => sut.Movies); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdTests.cs new file mode 100644 index 00000000..3ce92e54 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/MovieIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovieIdTests +{ + private readonly MovieIdFixture _movieIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + MovieId movieId = MovieId.CreateUnique(); + + // Assert + Assert.NotNull(movieId); + Assert.NotEqual(default, movieId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + MovieId movieId = MovieId.Create(value); + + // Assert + Assert.Equal(value, movieId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + MovieId firstId = _movieIdFixture.Create(value); + MovieId secondId = _movieIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + MovieId firstId = _movieIdFixture.Create(); + MovieId secondId = _movieIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs new file mode 100644 index 00000000..c855ebe0 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/MovieLibraryAggregate/ValueObjects/VideoMetadataTests.cs @@ -0,0 +1,162 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class VideoMetadataTests +{ + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + private readonly VideoMetadataFixture _videoMetadataFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet() + { + // Act + Result result = VideoMetadata.Create( + "Inception", + Optional.Some("Inception (Original)"), + durationInSeconds: 8880, + "1920x1080", + Optional.Some("A thief who steals corporate secrets."), + _releaseInfoFixture.Create(), + Optional.Some(_languageInfoFixture.Create()), + Optional.None(), + Optional.Some(24), + Optional.Some("H.264"), + Optional.Some("AAC"), + [_genreFixture.Create(name: "Action")], + [_tagFixture.Create(name: "heist")]); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Inception", result.Value.Title); + Assert.Equal("Inception (Original)", result.Value.OriginalTitle.Value); + Assert.Equal(8880, result.Value.DurationInSeconds); + Assert.Equal("1920x1080", result.Value.Resolution); + Assert.Equal("A thief who steals corporate secrets.", result.Value.Description.Value); + Assert.Equal(24, result.Value.FrameRate.Value); + Assert.Equal("H.264", result.Value.VideoCodec.Value); + Assert.Equal("AAC", result.Value.AudioCodec.Value); + Assert.Single(result.Value.Genres); + Assert.Single(result.Value.Tags); + Assert.True(result.Value.Language.HasValue); + Assert.False(result.Value.OriginalLanguage.HasValue); + } + + [Fact] + public void Create_WhenResolutionIsNull_ShouldThrowArgumentNullException() + { + // Act & Assert + Assert.Throws(() => VideoMetadata.Create( + "Inception", + Optional.None(), + durationInSeconds: 8880, + null!, + Optional.None(), + _releaseInfoFixture.Create(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None(), + [], + [])); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + VideoMetadata first = _videoMetadataFixture.Create( + title: "Inception", + originalTitle: Optional.None(), + durationInSeconds: 8880, + resolution: "1920x1080", + description: Optional.None(), + releaseInfo: releaseInfo, + language: Optional.None(), + originalLanguage: Optional.None(), + frameRate: Optional.None(), + videoCodec: Optional.None(), + audioCodec: Optional.None(), + genres: [], + tags: []); + VideoMetadata second = _videoMetadataFixture.Create( + title: "Inception", + originalTitle: Optional.None(), + durationInSeconds: 8880, + resolution: "1920x1080", + description: Optional.None(), + releaseInfo: releaseInfo, + language: Optional.None(), + originalLanguage: Optional.None(), + frameRate: Optional.None(), + videoCodec: Optional.None(), + audioCodec: Optional.None(), + genres: [], + tags: []); + + // Act + bool result = first.Equals(second); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentDuration_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + VideoMetadata first = _videoMetadataFixture.Create( + title: "Inception", + originalTitle: Optional.None(), + durationInSeconds: 8880, + resolution: "1920x1080", + description: Optional.None(), + releaseInfo: releaseInfo, + language: Optional.None(), + originalLanguage: Optional.None(), + frameRate: Optional.None(), + videoCodec: Optional.None(), + audioCodec: Optional.None(), + genres: [], + tags: []); + VideoMetadata second = _videoMetadataFixture.Create( + title: "Inception", + originalTitle: Optional.None(), + durationInSeconds: 8881, + resolution: "1920x1080", + description: Optional.None(), + releaseInfo: releaseInfo, + language: Optional.None(), + originalLanguage: Optional.None(), + frameRate: Optional.None(), + videoCodec: Optional.None(), + audioCodec: Optional.None(), + genres: [], + tags: []); + + // Act + bool result = first.Equals(second); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryServiceTests.cs new file mode 100644 index 00000000..b54e9f0f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/Services/VideoLibraryServiceTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.MovieLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class VideoLibraryServiceTests +{ + [Fact] + public void Constructor_WhenCalled_ShouldSetInjectedServices() + { + // Arrange + IMovieLibraryService movieLibraryService = Substitute.For(); + ITvShowLibraryService tvShowLibraryService = Substitute.For(); + + // Act + VideoLibraryService sut = new(movieLibraryService, tvShowLibraryService); + + // Assert + Assert.Same(movieLibraryService, sut.MovieLibraryService); + Assert.Same(tvShowLibraryService, sut.TvShowLibraryService); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/EpisodeTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/EpisodeTests.cs new file mode 100644 index 00000000..f0ec0802 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/EpisodeTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpisodeTests +{ + private readonly EpisodeIdFixture _episodeIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetId() + { + // Arrange + EpisodeId id = _episodeIdFixture.Create(); + + // Act + Episode episode = new(id); + + // Assert + Assert.Equal(id, episode.Id); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/SeasonTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/SeasonTests.cs new file mode 100644 index 00000000..43827ce3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Entities/SeasonTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SeasonTests +{ + private readonly SeasonIdFixture _seasonIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetId() + { + // Arrange + SeasonId id = _seasonIdFixture.Create(); + + // Act + Season season = new(id); + + // Assert + Assert.Equal(id, season.Id); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryServiceTests.cs new file mode 100644 index 00000000..675fdabb --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/Services/TvShowLibraryServiceTests.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TvShowLibraryServiceTests +{ + [Fact] + public void TvShows_WhenAccessed_ShouldThrowNotImplementedException() + { + // Arrange + TvShowLibraryService sut = new(); + + // Act & Assert + Assert.Throws(() => sut.TvShows); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShowTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShowTests.cs new file mode 100644 index 00000000..828ee7da --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/TvShowTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TvShowTests +{ + private readonly TvShowIdFixture _tvShowIdFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetId() + { + // Arrange + TvShowId id = _tvShowIdFixture.Create(); + + // Act + TvShow tvShow = new(id); + + // Assert + Assert.Equal(id, tvShow.Id); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdTests.cs new file mode 100644 index 00000000..33a9dc22 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/EpisodeIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class EpisodeIdTests +{ + private readonly EpisodeIdFixture _episodeIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + EpisodeId episodeId = EpisodeId.CreateUnique(); + + // Assert + Assert.NotNull(episodeId); + Assert.NotEqual(default, episodeId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + EpisodeId episodeId = EpisodeId.Create(value); + + // Assert + Assert.Equal(value, episodeId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + EpisodeId firstId = _episodeIdFixture.Create(value); + EpisodeId secondId = _episodeIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + EpisodeId firstId = _episodeIdFixture.Create(); + EpisodeId secondId = _episodeIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdTests.cs new file mode 100644 index 00000000..8b7b258d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/SeasonIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SeasonIdTests +{ + private readonly SeasonIdFixture _seasonIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + SeasonId seasonId = SeasonId.CreateUnique(); + + // Assert + Assert.NotNull(seasonId); + Assert.NotEqual(default, seasonId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + SeasonId seasonId = SeasonId.Create(value); + + // Assert + Assert.Equal(value, seasonId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + SeasonId firstId = _seasonIdFixture.Create(value); + SeasonId secondId = _seasonIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + SeasonId firstId = _seasonIdFixture.Create(); + SeasonId secondId = _seasonIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdTests.cs new file mode 100644 index 00000000..5c80d9c8 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/VideoLibraryBoundedContext/TvShowLibraryAggregate/ValueObjects/TvShowIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.VideoLibraryBoundedContext.TvShowLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class TvShowIdTests +{ + private readonly TvShowIdFixture _tvShowIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + TvShowId tvShowId = TvShowId.CreateUnique(); + + // Assert + Assert.NotNull(tvShowId); + Assert.NotEqual(default, tvShowId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + TvShowId tvShowId = TvShowId.Create(value); + + // Assert + Assert.Equal(value, tvShowId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + TvShowId firstId = _tvShowIdFixture.Create(value); + TvShowId secondId = _tvShowIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + TvShowId firstId = _tvShowIdFixture.Create(); + TvShowId secondId = _tvShowIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeriesTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeriesTests.cs new file mode 100644 index 00000000..c7d662c7 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Entities/BookSeriesTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesTests +{ + private readonly BookFixture _bookFixture = new(); + private readonly BookSeriesIdFixture _bookSeriesIdFixture = new(); + private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new(); + private readonly BookSeriesFixture _bookSeriesFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidData_ShouldCreateSeries() + { + // Act + Result result = BookSeries.Create(_writtenContentMetadataFixture.Create(), isComplete: false, []); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.IsComplete); + Assert.Empty(result.Value.Books); + Assert.NotEqual(default, result.Value.Id.Value); + } + + [Fact] + public void Create_WhenCalledWithPreExistingId_ShouldCreateSeriesWithThatId() + { + // Arrange + Guid id = Guid.NewGuid(); + + // Act + Result result = BookSeries.Create(_bookSeriesIdFixture.Create(id), _writtenContentMetadataFixture.Create(), isComplete: true, []); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(id, result.Value.Id.Value); + Assert.True(result.Value.IsComplete); + } + + [Fact] + public void AddBook_WhenBookIsNotInSeries_ShouldAddBookAndReturnCreated() + { + // Arrange + BookSeries series = _bookSeriesFixture.Create(); + Book book = _bookFixture.Create(); + + // Act + Result result = series.AddBook(book); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Created, result.Value); + Assert.Single(series.Books); + Assert.Contains(book, series.Books); + } + + [Fact] + public void AddBook_WhenBookIsAlreadyInSeries_ShouldReturnError() + { + // Arrange + BookSeries series = _bookSeriesFixture.Create(); + Book book = _bookFixture.Create(); + series.AddBook(book); + + // Act + Result result = series.AddBook(book); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.TheBookIsAlreadyInTheSeries, result.FirstError); + Assert.Single(series.Books); + } + + [Fact] + public void RemoveBook_WhenBookIsInSeries_ShouldRemoveBookAndReturnDeleted() + { + // Arrange + BookSeries series = _bookSeriesFixture.Create(); + Book book = _bookFixture.Create(); + series.AddBook(book); + + // Act + Result result = series.RemoveBook(book); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + Assert.Empty(series.Books); + } + + [Fact] + public void RemoveBook_WhenBookIsNotInSeries_ShouldReturnError() + { + // Arrange + BookSeries series = _bookSeriesFixture.Create(); + Book book = _bookFixture.Create(); + + // Act + Result result = series.RemoveBook(book); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.TheBookIsNotInTheSeries, result.FirstError); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs new file mode 100644 index 00000000..60e8122d --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/BookLibraryServiceTests.cs @@ -0,0 +1,24 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLibraryServiceTests +{ + [Fact] + public void Books_WhenAccessed_ShouldThrowNotImplementedException() + { + // Arrange + BookLibraryService sut = new(); + + // Act & Assert + Assert.Throws(() => sut.Books); + } +} 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 new file mode 100644 index 00000000..dc1b200e --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScannerTests.cs @@ -0,0 +1,150 @@ +#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; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services.Scanners; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLibraryTypeScannerTests +{ + private readonly IMediaLibraryScanJobFactory _mockJobFactory = Substitute.For(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void SupportedLibraryType_ShouldBeBook() + { + // Arrange + BookLibraryTypeScanner sut = new(_mockJobFactory); + + // Act & Assert + Assert.Equal(LibraryType.Book, sut.SupportedLibraryType); + } + + [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() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + TestScanJob discoveryJob = CreateJob(); + TestScanJob diffJob = CreateJob(); + TestScanJob hashJob = CreateJob(); + TestScanJob saveJob = CreateJob(); + TestScanJob enrichmentJob = CreateJob(); + BookLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + List rootJobs = [.. sut.CreateScanJobsForLibrary(libraryId, downloadMetadataFromWeb: true)]; + + // Assert + IMediaLibraryScanJob rootJob = Assert.Single(rootJobs); + Assert.Same(discoveryJob, rootJob); + Assert.Contains(saveJob, hashJob.Children); + Assert.Contains(enrichmentJob, saveJob.Children); + Assert.Contains(saveJob, enrichmentJob.Parents); + _mockJobFactory.Received(1).CreateJob(libraryId); + } + + [Fact] + public void CreateScanJobsForLibrary_WhenCalled_ShouldCreateJobsForTheLibrary() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + CreateJob(); + CreateJob(); + CreateJob(); + CreateJob(); + BookLibraryTypeScanner sut = new(_mockJobFactory); + + // Act + _ = sut.CreateScanJobsForLibrary(libraryId, downloadMetadataFromWeb: false).ToList(); + + // Assert + _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 + { + TestScanJob job = new() + { + ScanId = _scanIdFixture.Create(), + UserId = _userIdFixture.Create(), + LibraryId = _libraryIdFixture.Create() + }; + _mockJobFactory.CreateJob(Arg.Any()).Returns((TJob)(object)job); + return job; + } + + /// + /// Concrete test implementation of the abstract class that satisfies all job interfaces. + /// + private sealed class TestScanJob : MediaLibraryScanJob, + IBooksFileSystemDiscoveryJob, + IMediaLibraryScanDiffJob, + IMediaLibraryScanHashJob, + IMediaLibraryScanResultsSaveJob, + IMediaLibraryScanMetadataEnrichmentJob + { + /// + /// Executes the payload of the media library scan job. + /// + /// The type of the input parameter. + /// The unique identifier of the media library scan job. + /// The input data to be processed. + /// Cancellation token that can be used to stop the execution. + /// A task that represents the asynchronous operation. + public override Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdTests.cs new file mode 100644 index 00000000..75eb4fdf --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookIdTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookIdTests +{ + private readonly BookIdFixture _bookIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + BookId bookId = BookId.CreateUnique(); + + // Assert + Assert.NotNull(bookId); + Assert.NotEqual(default, bookId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + BookId bookId = BookId.Create(value); + + // Assert + Assert.Equal(value, bookId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + BookId firstId = _bookIdFixture.Create(value); + BookId secondId = _bookIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + BookId firstId = _bookIdFixture.Create(); + BookId secondId = _bookIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs new file mode 100644 index 00000000..6eed5bbe --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookLibraryIdTests.cs @@ -0,0 +1,72 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookLibraryIdTests +{ + private readonly BookLibraryIdFixture _bookLibraryIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + Result result = BookLibraryId.CreateUnique(); + + // Assert + Assert.False(result.IsFailure); + Assert.NotEqual(default, result.Value.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + Result result = BookLibraryId.Create(value); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(value, result.Value.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + BookLibraryId firstId = _bookLibraryIdFixture.Create(value); + BookLibraryId secondId = _bookLibraryIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + BookLibraryId firstId = _bookLibraryIdFixture.Create(); + BookLibraryId secondId = _bookLibraryIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingTests.cs new file mode 100644 index 00000000..dd71cb90 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookRatingTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookRatingTests +{ + private readonly BookRatingFixture _bookRatingFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateRating() + { + // Act + Result result = BookRating.Create( + value: 4.5m, + maxValue: 5, + Optional.Some(BookRatingSource.Goodreads), + Optional.Some(100)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(4.5m, result.Value.Value); + Assert.Equal(5, result.Value.MaxValue); + Assert.True(result.Value.Source.HasValue); + Assert.Equal(BookRatingSource.Goodreads, result.Value.Source.Value); + Assert.True(result.Value.VoteCount.HasValue); + Assert.Equal(100, result.Value.VoteCount.Value); + } + + [Theory] + [InlineData(-1)] // negative value + [InlineData(-0.5)] // negative fractional value + public void Create_WhenValueIsNegative_ShouldReturnError(double value) + { + // Act + Result result = BookRating.Create((decimal)value, maxValue: 5, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenMaxValueIsNegative_ShouldReturnError() + { + // Act + Result result = BookRating.Create(value: 4.5m, maxValue: -5, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueMustBePositive, result.FirstError); + } + + [Fact] + public void Create_WhenValueExceedsMaxValue_ShouldReturnError() + { + // Act + Result result = BookRating.Create(value: 6, maxValue: 5, Optional.None(), Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Metadata.RatingValueCannotBeGreaterThanMaxValue, result.FirstError); + } + + [Fact] + public void AsPercentage_WhenCalled_ShouldReturnValueAsPercentageOfMaxValue() + { + // Arrange + BookRating rating = _bookRatingFixture.Create(value: 4.5m, maxValue: 5); + + // Act + decimal result = rating.AsPercentage(); + + // Assert + Assert.Equal(90, result); + } + + [Fact] + public void ToString_WhenSourceAndVoteCountArePresent_ShouldIncludeThem() + { + // Arrange + BookRating rating = _bookRatingFixture.Create( + value: 4.5m, + maxValue: 5, + source: Optional.Some(BookRatingSource.Goodreads), + voteCount: Optional.Some(100)); + + // Act + string result = rating.ToString(); + + // Assert + Assert.Equal("4.5/5 (Goodreads) [100 votes]", result); + } + + [Fact] + public void ToString_WhenSourceAndVoteCountAreAbsent_ShouldReturnBaseString() + { + // Arrange + BookRating rating = _bookRatingFixture.Create( + value: 4.5m, + maxValue: 5, + source: Optional.None(), + voteCount: Optional.None()); + + // Act + string result = rating.ToString(); + + // Assert + Assert.Equal("4.5/5", result); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + BookRating firstRating = _bookRatingFixture.Create( + value: 4.5m, + maxValue: 5, + source: Optional.Some(BookRatingSource.Goodreads), + voteCount: Optional.Some(100)); + BookRating secondRating = _bookRatingFixture.Create( + value: 4.5m, + maxValue: 5, + source: Optional.Some(BookRatingSource.Goodreads), + voteCount: Optional.Some(100)); + + // Act + bool result = firstRating.Equals(secondRating); + + // Assert + Assert.True(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdTests.cs new file mode 100644 index 00000000..39375042 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/BookSeriesIdTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookSeriesIdTests +{ + private readonly BookSeriesIdFixture _bookSeriesIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + BookSeriesId seriesId = BookSeriesId.CreateUnique(); + + // Assert + Assert.NotNull(seriesId); + Assert.NotEqual(default, seriesId.Value); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + BookSeriesId seriesId = BookSeriesId.Create(value); + + // Assert + Assert.Equal(value, seriesId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + BookSeriesId firstId = _bookSeriesIdFixture.Create(value); + BookSeriesId secondId = _bookSeriesIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + BookSeriesId firstId = _bookSeriesIdFixture.Create(); + BookSeriesId secondId = _bookSeriesIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs new file mode 100644 index 00000000..1c2a7799 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/IsbnTests.cs @@ -0,0 +1,184 @@ +#region ========================================================================= USING ===================================================================================== +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class IsbnTests +{ + private readonly IsbnFixture _isbnFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidIsbn10_ShouldCreateIsbn10() + { + // Act + Result result = Isbn.Create("0-306-40615-2", IsbnFormat.Isbn10); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("0-306-40615-2", result.Value.Value); + Assert.Equal(IsbnFormat.Isbn10, result.Value.Format); + } + + [Fact] + public void Create_WhenCalledWithValidIsbn13_ShouldCreateIsbn13() + { + // Act + Result result = Isbn.Create("978-0-306-40615-7", IsbnFormat.Isbn13); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("978-0-306-40615-7", result.Value.Value); + Assert.Equal(IsbnFormat.Isbn13, result.Value.Format); + } + + [Theory] + [InlineData(null)] // null ISBN value + [InlineData("")] // empty ISBN value + [InlineData(" ")] // whitespace ISBN value + public void Create_WhenValueIsNullOrWhitespace_ShouldReturnError(string? value) + { + // Act + Result result = Isbn.Create(value, IsbnFormat.Isbn10); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.IsbnValueCannotBeEmpty, result.FirstError); + } + + [Fact] + public void Create_WhenFormatIsUnknown_ShouldReturnError() + { + // Act + Result result = Isbn.Create("0-306-40615-2", (IsbnFormat)999); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.UnknownIsbnFormat, result.FirstError); + } + + [Fact] + public void Create_WhenIsbn10HasInvalidCheckDigit_ShouldReturnError() + { + // Act + Result result = Isbn.Create("0-306-40615-3", IsbnFormat.Isbn10); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.InvalidIsbn10Format, result.FirstError); + } + + [Fact] + public void Create_WhenIsbn13HasInvalidCheckDigit_ShouldReturnError() + { + // Act + Result result = Isbn.Create("978-0-306-40615-8", IsbnFormat.Isbn13); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.InvalidIsbn13Format, result.FirstError); + } + + [Fact] + public void Create_WhenIsbn10HasWrongLength_ShouldReturnError() + { + // Act + Result result = Isbn.Create("123456789", IsbnFormat.Isbn10); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.WrittenContent.InvalidIsbn10Format, result.FirstError); + } + + [Theory] + [InlineData("0-306-40615-2")] // valid ISBN-10 with hyphens + [InlineData("0306406152")] // valid ISBN-10 without hyphens + public void IsValidIsbn10_WhenValueIsValid_ShouldReturnTrue(string isbn) + { + // Act + bool result = Isbn.IsValidIsbn10(isbn); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("0-306-40615-3")] // invalid check digit + [InlineData("030640615")] // too short + [InlineData("03064061523")] // too long + [InlineData("")] // empty value + [InlineData("ISBN 0-306-40615-2")] // ISBN prefix is not stripped by the checksum computation + public void IsValidIsbn10_WhenValueIsInvalid_ShouldReturnFalse(string isbn) + { + // Act + bool result = Isbn.IsValidIsbn10(isbn); + + // Assert + Assert.False(result); + } + + [Theory] + [InlineData("978-0-306-40615-7")] // valid ISBN-13 with hyphens + [InlineData("9780306406157")] // valid ISBN-13 without hyphens + [InlineData("979-0-306-40615-6")] // valid ISBN-13 with 979 prefix + public void IsValidIsbn13_WhenValueIsValid_ShouldReturnTrue(string isbn) + { + // Act + bool result = Isbn.IsValidIsbn13(isbn); + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData("978-0-306-40615-8")] // invalid check digit + [InlineData("978030640615")] // too short + [InlineData("97803064061578")] // too long + [InlineData("")] // empty value + [InlineData("ISBN 978-0-306-40615-7")] // ISBN prefix is not stripped by the checksum computation + public void IsValidIsbn13_WhenValueIsInvalid_ShouldReturnFalse(string isbn) + { + // Act + bool result = Isbn.IsValidIsbn13(isbn); + + // Assert + Assert.False(result); + } + + [Fact] + public void Equals_WithSameValueAndFormat_ShouldReturnTrue() + { + // Arrange + Isbn firstIsbn = _isbnFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10); + Isbn secondIsbn = _isbnFixture.Create(value: "0-306-40615-2", format: IsbnFormat.Isbn10); + + // Act + bool result = firstIsbn.Equals(secondIsbn); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + Isbn firstIsbn = _isbnFixture.Create(); + Isbn secondIsbn = _isbnFixture.Create(); + + // Act + bool result = firstIsbn.Equals(secondIsbn); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataTests.cs new file mode 100644 index 00000000..7ffc3b65 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/ValueObjects/WrittenContentMetadataTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Common.ValueObjects.Metadata; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Common.ValueObjects.Metadata; +using Lumina.Domain.Fixtures.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentMetadataTests +{ + private readonly GenreFixture _genreFixture = new(); + private readonly TagFixture _tagFixture = new(); + private readonly ReleaseInfoFixture _releaseInfoFixture = new(); + private readonly LanguageInfoFixture _languageInfoFixture = new(); + private readonly WrittenContentMetadataFixture _writtenContentMetadataFixture = new(); + + [Fact] + public void Create_WhenCalledWithValidValues_ShouldCreateMetadataWithAllPropertiesSet() + { + // Act + Result result = WrittenContentMetadata.Create( + "Dune", + Optional.Some("Dune (Original)"), + Optional.Some("A classic science fiction novel."), + _releaseInfoFixture.Create(), + [_genreFixture.Create(name: "Science Fiction")], + [_tagFixture.Create(name: "classic")], + Optional.Some(_languageInfoFixture.Create()), + Optional.None(), + Optional.Some("Chilton Books"), + Optional.Some(412)); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Dune", result.Value.Title); + Assert.Equal("Dune (Original)", result.Value.OriginalTitle.Value); + Assert.Equal("A classic science fiction novel.", result.Value.Description.Value); + Assert.Single(result.Value.Genres); + Assert.Single(result.Value.Tags); + Assert.True(result.Value.Language.HasValue); + Assert.False(result.Value.OriginalLanguage.HasValue); + Assert.True(result.Value.Publisher.HasValue); + Assert.Equal("Chilton Books", result.Value.Publisher.Value); + Assert.True(result.Value.PageCount.HasValue); + Assert.Equal(412, result.Value.PageCount.Value); + } + + [Fact] + public void Create_WhenCalledWithOptionalValuesAbsent_ShouldCreateMetadataWithoutThem() + { + // Act + Result result = WrittenContentMetadata.Create( + "Dune", + Optional.None(), + Optional.None(), + _releaseInfoFixture.Create(), + [], + [], + Optional.None(), + Optional.None(), + Optional.None(), + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.OriginalTitle.HasValue); + Assert.False(result.Value.Publisher.HasValue); + Assert.False(result.Value.PageCount.HasValue); + } + + [Fact] + public void Equals_WithSameValues_ShouldReturnTrue() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + WrittenContentMetadata firstResult = _writtenContentMetadataFixture.Create( + title: "Dune", + originalTitle: Optional.None(), + description: Optional.None(), + releaseInfo: releaseInfo, + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + publisher: Optional.None(), + pageCount: Optional.None()); + WrittenContentMetadata secondResult = _writtenContentMetadataFixture.Create( + title: "Dune", + originalTitle: Optional.None(), + description: Optional.None(), + releaseInfo: releaseInfo, + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + publisher: Optional.None(), + pageCount: Optional.None()); + + // Assert + Assert.Equal(firstResult, secondResult); + } + + [Fact] + public void Equals_WithDifferentPublisher_ShouldReturnFalse() + { + // Arrange + ReleaseInfo releaseInfo = _releaseInfoFixture.Create(); + + // Act + WrittenContentMetadata firstResult = _writtenContentMetadataFixture.Create( + title: "Dune", + originalTitle: Optional.None(), + description: Optional.None(), + releaseInfo: releaseInfo, + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + publisher: Optional.None(), + pageCount: Optional.None()); + WrittenContentMetadata secondResult = _writtenContentMetadataFixture.Create( + title: "Dune", + originalTitle: Optional.None(), + description: Optional.None(), + releaseInfo: releaseInfo, + genres: [], + tags: [], + language: Optional.None(), + originalLanguage: Optional.None(), + publisher: Optional.Some("Other Publisher"), + pageCount: Optional.None()); + + // Assert + Assert.NotEqual(firstResult, secondResult); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryServiceTests.cs new file mode 100644 index 00000000..5498c773 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/WrittenContentLibraryBoundedContext/Services/WrittenContentLibraryServiceTests.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class WrittenContentLibraryServiceTests +{ + [Fact] + public void Constructor_WhenCalled_ShouldSetInjectedService() + { + // Arrange + IBookLibraryService bookLibraryService = Substitute.For(); + + // Act + WrittenContentLibraryService sut = new(bookLibraryService); + + // Assert + Assert.Same(bookLibraryService, sut.BookLibraryService); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/Services/MediaLibraryServiceTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Services/MediaLibraryServiceTests.cs new file mode 100644 index 00000000..dbf6d324 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/Services/MediaLibraryServiceTests.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.VideoLibraryBoundedContext.Services; +using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Services; +using Lumina.Domain.Core.Services; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.Services; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryServiceTests +{ + [Fact] + public void Constructor_WhenCalled_ShouldSetInjectedServices() + { + // Arrange + IVideoLibraryService videoLibraryService = Substitute.For(); + IWrittenContentLibraryService writtenContentLibraryService = Substitute.For(); + + // Act + MediaLibraryService sut = new(videoLibraryService, writtenContentLibraryService); + + // Assert + Assert.Same(videoLibraryService, sut.VideoLibraryService); + Assert.Same(writtenContentLibraryService, sut.WrittenContentLibraryService); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs new file mode 100644 index 00000000..d38f7e75 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs @@ -0,0 +1,84 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; +using Lumina.Infrastructure.Common.DependencyInjection; +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Infrastructure.Core.Security; +using Lumina.Infrastructure.Core.Time; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class InfrastructureLayerServicesTests +{ + [Fact] + public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterCoreInfrastructureServices() + { + // Arrange + IServiceCollection services = new ServiceCollection(); + IConfiguration configuration = CreateConfiguration(); + + // Act + services.AddInfrastructureLayerServices(configuration); + + // Assert + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDateTimeProvider) && descriptor.ImplementationType == typeof(DateTimeProvider)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginManager)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IPluginSettingsStore)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventsQueue)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IDomainEventPublisher)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanQueue)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibrariesScanCancellationTracker)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IMediaLibraryScanProgressNotifier)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IHostedService)); + } + + [Fact] + public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterAllValidatorsFromTheAssembly() + { + // Arrange + IServiceCollection services = new ServiceCollection(); + IConfiguration configuration = CreateConfiguration(); + + // Act + services.AddInfrastructureLayerServices(configuration); + + // Assert + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator)); + Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator)); + } + + /// + /// Creates an in-memory configuration pointing the plugins directory to a non-existent folder, so no plugin assemblies are loaded. + /// + /// The created configuration. + private static IConfiguration CreateConfiguration() + { + Dictionary configurationValues = new() + { + [$"{PluginsSettingsDto.SECTION_NAME}:Directory"] = "non-existent-plugins-directory" + }; + return new ConfigurationBuilder().AddInMemoryCollection(configurationValues).Build(); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventsQueueTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventsQueueTests.cs new file mode 100644 index 00000000..fdb10de6 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DomainEvents/DomainEventsQueueTests.cs @@ -0,0 +1,109 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Infrastructure.Common.DomainEvents; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.DomainEvents; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DomainEventsQueueTests +{ + private readonly DomainEventsQueue _sut = new(); + + [Fact] + public void TryDequeue_WhenQueueIsEmpty_ShouldReturnFalse() + { + // Act + bool result = _sut.TryDequeue(out IDomainEvent domainEvent); + + // Assert + Assert.False(result); + Assert.Null(domainEvent); + } + + [Fact] + public void Enqueue_WhenCalled_ShouldDequeueTheSameDomainEvent() + { + // Arrange + TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow); + + // Act + _sut.Enqueue(domainEvent); + bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent); + + // Assert + Assert.True(result); + Assert.Same(domainEvent, dequeuedEvent); + } + + [Fact] + public void Enqueue_WhenCalledMultipleTimes_ShouldDequeueInFifoOrder() + { + // Arrange + TestDomainEvent firstEvent = new(Guid.NewGuid(), DateTime.UtcNow); + TestDomainEvent secondEvent = new(Guid.NewGuid(), DateTime.UtcNow); + TestDomainEvent thirdEvent = new(Guid.NewGuid(), DateTime.UtcNow); + + // Act + _sut.Enqueue(firstEvent); + _sut.Enqueue(secondEvent); + _sut.Enqueue(thirdEvent); + _sut.TryDequeue(out IDomainEvent firstDequeued); + _sut.TryDequeue(out IDomainEvent secondDequeued); + _sut.TryDequeue(out IDomainEvent thirdDequeued); + + // Assert + Assert.Same(firstEvent, firstDequeued); + Assert.Same(secondEvent, secondDequeued); + Assert.Same(thirdEvent, thirdDequeued); + } + + [Fact] + public void Enqueue_WhenCalledWithMultipleEventTypes_ShouldDequeueAllTypes() + { + // Arrange + TestDomainEvent testEvent = new(Guid.NewGuid(), DateTime.UtcNow); + NestedTestDomainEvent nestedEvent = new(Guid.NewGuid(), DateTime.UtcNow); + + // Act + _sut.Enqueue(testEvent); + _sut.Enqueue(nestedEvent); + _sut.TryDequeue(out IDomainEvent firstDequeued); + _sut.TryDequeue(out IDomainEvent secondDequeued); + + // Assert + Assert.Same(testEvent, firstDequeued); + Assert.Same(nestedEvent, secondDequeued); + } + + [Fact] + public void TryDequeue_WhenAllEventsWereDequeued_ShouldReturnFalseOnNextCall() + { + // Arrange + TestDomainEvent domainEvent = new(Guid.NewGuid(), DateTime.UtcNow); + _sut.Enqueue(domainEvent); + + // Act + _sut.TryDequeue(out _); + bool result = _sut.TryDequeue(out IDomainEvent dequeuedEvent); + + // Assert + Assert.False(result); + Assert.Null(dequeuedEvent); + } + + /// + /// Test domain event used by the queue tests. + /// + private sealed record TestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent; + + /// + /// A second test domain event used by the queue tests. + /// + private sealed record NestedTestDomainEvent(Guid Id, DateTime OccurredOnUtc) : IDomainEvent; +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ExceptionUtilitiesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ExceptionUtilitiesTests.cs new file mode 100644 index 00000000..50f79113 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Utilities/ExceptionUtilitiesTests.cs @@ -0,0 +1,121 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Utilities; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Utilities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ExceptionUtilitiesTests +{ + [Fact] + public void AggregateMessages_WhenCalledWithNestedException_ShouldConcatenateAllMessages() + { + // Arrange + Exception exception = new("outer", new InvalidOperationException("inner", new ArgumentException("deepest"))); + + // Act + string result = exception.AggregateMessages(); + + // Assert + Assert.Contains("outer", result); + Assert.Contains("inner", result); + Assert.Contains("deepest", result); + Assert.Contains(" -> ", result); + } + + [Fact] + public void AggregateMessages_WhenCalledWithSingleException_ShouldReturnItsMessageWithArrow() + { + // Arrange + Exception exception = new("only-message"); + + // Act + string result = exception.AggregateMessages(); + + // Assert + Assert.Contains("only-message", result); + Assert.Contains(" -> ", result); + } + + [Fact] + public void GetInnerExceptions_WhenExceptionIsNull_ShouldReturnEmptySequence() + { + // Act + IEnumerable result = ((Exception)null!).GetInnerExceptions(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void GetInnerExceptions_WhenExceptionHasNestedInners_ShouldReturnAllLevels() + { + // Arrange + Exception exception = new("first", new InvalidOperationException("second", new ArgumentException("third"))); + + // Act + List result = [.. exception.GetInnerExceptions()]; + + // Assert + Assert.Equal(3, result.Count); + Assert.Equal("first", result[0].Message); + Assert.Equal("second", result[1].Message); + Assert.Equal("third", result[2].Message); + } + + [Fact] + public void GetInnerExceptions_WhenChainExceedsMaximumDepth_ShouldStopAtMaximumDepth() + { + // Arrange + Exception exception = new("level-1", new Exception("level-2", new Exception("level-3", new Exception("level-4", new Exception("level-5", new Exception("level-6")))))); + + // Act + List result = [.. exception.GetInnerExceptions(maximumDepth: 3)]; + + // Assert + Assert.Equal(3, result.Count); + Assert.Equal(["level-1", "level-2", "level-3"], result.Select(inner => inner.Message)); + } + + [Fact] + public void GetInnerExceptions_WhenExceptionIsAggregate_ShouldReturnItsInnerExceptions() + { + // Arrange + AggregateException exception = new( + "aggregate", + [new InvalidOperationException("first-inner", new Exception("first-deep")), new ArgumentException("second-inner")]); + + // Act + List result = [.. exception.GetInnerExceptions()]; + + // Assert + // the aggregate exception itself, its inner exceptions and their inners are traversed, and the first inner exception + // is also reachable through the regular InnerException chain, so it is yielded twice + Assert.Equal(6, result.Count); + Assert.Contains(result, inner => inner is AggregateException); + Assert.Equal(2, result.Count(inner => inner.Message == "first-inner")); + Assert.Equal(2, result.Count(inner => inner.Message == "first-deep")); + Assert.Single(result, inner => inner.Message == "second-inner"); + } + + [Fact] + public void AggregateMessage_WhenCalled_ShouldContainMessageAndCallStack() + { + // Arrange + Exception exception = new("some-message"); + + // Act + string result = exception.AggregateMessage(); + + // Assert + Assert.Contains("Message: some-message", result); + Assert.Contains("CallStack:", result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CorsSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CorsSettingsDtoValidatorTests.cs new file mode 100644 index 00000000..588b8248 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/CorsSettingsDtoValidatorTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Models.DTO.Configuration; +using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CorsSettingsDtoValidatorTests +{ + private readonly CorsSettingsDtoValidator _validator = new(); + private readonly CorsSettingsDtoFixture _corsSettingsDtoFixture = new(); + + [Fact] + public void Validate_WhenOriginsAreValidAbsoluteUrls_ShouldNotHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com", "http://localhost:4200"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenOriginIsWildcard_ShouldNotHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["*"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenAllowedOriginsIsEmpty_ShouldHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create([]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.CorsOriginsCannotBeEmpty.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenOriginHasTrailingSlash_ShouldHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://app.example.com/"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenOriginHasNoScheme_ShouldHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["app.example.com"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenOriginHasUnsupportedScheme_ShouldHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["ftp://app.example.com"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenOneOriginIsInvalid_ShouldHaveValidationErrorForThatOrigin() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create(["https://valid.example.com", "invalid-origin"]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.CorsOriginIsInvalid.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenOriginIsEmptyString_ShouldHaveValidationError() + { + // Arrange + CorsSettingsDto model = _corsSettingsDtoFixture.Create([""]); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Equal(2, result.Count); + Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginsCannotBeEmpty.Description); + Assert.Contains(result, error => error.Description == Errors.Configuration.CorsOriginIsInvalid.Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/PluginsSettingsDtoValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/PluginsSettingsDtoValidatorTests.cs new file mode 100644 index 00000000..0d1610b1 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/PluginsSettingsDtoValidatorTests.cs @@ -0,0 +1,62 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Common.Errors; +using Lumina.Infrastructure.Common.Validators; +using Lumina.Infrastructure.Fixtures.Common.Models.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Validators; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginsSettingsDtoValidatorTests +{ + private readonly PluginsSettingsDtoValidator _validator = new(); + private readonly PluginsSettingsDtoFixture _pluginsSettingsDtoFixture = new(); + + [Fact] + public void Validate_WhenDirectoryProvided_ShouldNotHaveValidationError() + { + // Arrange + PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: "/path/to/plugins"); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void Validate_WhenDirectoryIsEmpty_ShouldHaveValidationError() + { + // Arrange + PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: string.Empty); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description); + } + + [Fact] + public void Validate_WhenDirectoryIsWhitespace_ShouldHaveValidationError() + { + // Arrange + PluginsSettingsDto model = _pluginsSettingsDtoFixture.Create(directory: " "); + + // Act + List result = _validator.Validate(model); + + // Assert + Assert.Single(result); + Assert.Equal(Errors.Configuration.PluginsDirectoryCannotBeEmpty.Description, result[0].Description); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs index c0d94a25..c5a2ade0 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/AuthorizationServiceTests.cs @@ -32,6 +32,7 @@ public class AuthorizationServiceTests private readonly IUserRepository _mockUserRepository; private readonly IAuthorizationPolicyFactory _mockAuthorizationPolicyFactory; private readonly AuthorizationService _sut; + private readonly AuthorizationServiceFixture _authorizationServiceFixture = new(); /// /// Initializes a new instance of the class. @@ -84,7 +85,7 @@ public class AuthorizationServiceTests public async Task HasPermissionAsync_WhenUserHasDirectPermission_ShouldReturnTrue() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanViewUsers]); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -107,7 +108,7 @@ public class AuthorizationServiceTests { "Admin", new[] { AuthorizationPermission.CanViewUsers } } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -125,7 +126,7 @@ public class AuthorizationServiceTests public async Task HasPermissionAsync_WhenUserHasNoPermissions_ShouldReturnFalse() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) .Returns(Result.From(user)); @@ -142,7 +143,7 @@ public class AuthorizationServiceTests public async Task HasPermissionAsync_WhenUserHasDifferentPermission_ShouldReturnFalse() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanDeleteUsers]); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -165,7 +166,7 @@ public class AuthorizationServiceTests { "Admin", new[] { AuthorizationPermission.CanViewUsers } } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanViewUsers], rolePermissions: rolePermissions); @@ -222,7 +223,7 @@ public class AuthorizationServiceTests { "Admin", Array.Empty() } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -245,7 +246,7 @@ public class AuthorizationServiceTests { "", Array.Empty() } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -263,7 +264,7 @@ public class AuthorizationServiceTests public async Task IsInRoleAsync_WhenUserHasNoRoles_ShouldReturnFalse() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) .Returns(Result.From(user)); @@ -442,7 +443,7 @@ public class AuthorizationServiceTests public async Task GetUserAuthorizationAsync_WhenUserHasNoRolesOrPermissions_ShouldReturnEmptySets() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions(); + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions(); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) .Returns(Result.From(user)); @@ -461,7 +462,7 @@ public class AuthorizationServiceTests public async Task GetUserAuthorizationAsync_WhenUserHasOnlyDirectPermissions_ShouldReturnCorrectPermissions() { // Arrange - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [ AuthorizationPermission.CanViewUsers, @@ -495,7 +496,7 @@ public class AuthorizationServiceTests } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: rolePermissions); _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) @@ -525,7 +526,7 @@ public class AuthorizationServiceTests } }; - UserEntity user = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity user = _authorizationServiceFixture.CreateUserWithPermissions( directPermissions: [AuthorizationPermission.CanRegisterUsers], rolePermissions: rolePermissions); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs index 5ed79e39..352f2f8b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/LibraryOwnership/LibraryOwnershipPolicyTests.cs @@ -6,9 +6,9 @@ using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership; using Lumina.Infrastructure.Fixtures.Core.Authorization; using NSubstitute; @@ -31,6 +31,8 @@ public class LibraryOwnershipPolicyTests private readonly IUserRepository _mockUserRepository; private readonly ILibraryRepository _mockLibraryRepository; private readonly LibraryOwnershipPolicy _sut; + private readonly AuthorizationServiceFixture _authorizationServiceFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -99,7 +101,7 @@ public class LibraryOwnershipPolicyTests public async Task EvaluateAsync_WhenUserIsAdmin_ShouldReturnTrue() { // Arrange - UserEntity adminUser = AuthorizationServiceFixture.CreateUserWithPermissions( + UserEntity adminUser = _authorizationServiceFixture.CreateUserWithPermissions( rolePermissions: new Dictionary> { { "Admin", [] } @@ -121,7 +123,7 @@ public class LibraryOwnershipPolicyTests { // Arrange Guid userId = Guid.NewGuid(); - UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions(); + UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) .Returns(Result.From(regularUser)); @@ -140,7 +142,7 @@ public class LibraryOwnershipPolicyTests { // Arrange Guid userId = Guid.NewGuid(); - UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions(); + UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); LibraryOwnershipPolicyContext context = new(Guid.NewGuid()); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) .Returns(Result.From(regularUser)); @@ -159,8 +161,8 @@ public class LibraryOwnershipPolicyTests { // Arrange Guid userId = Guid.NewGuid(); - UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions(); - LibraryEntity library = CreateLibrary(userId); + UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); + LibraryEntity library = _libraryEntityFixture.Create(userId: userId); LibraryOwnershipPolicyContext context = new(library.Id); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) .Returns(Result.From(regularUser)); @@ -179,8 +181,8 @@ public class LibraryOwnershipPolicyTests { // Arrange Guid userId = Guid.NewGuid(); - UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions(); - LibraryEntity library = CreateLibrary(Guid.NewGuid()); + UserEntity regularUser = _authorizationServiceFixture.CreateUserWithPermissions(); + LibraryEntity library = _libraryEntityFixture.Create(userId: Guid.NewGuid()); LibraryOwnershipPolicyContext context = new(library.Id); _mockUserRepository.GetByIdAsync(userId, Arg.Any()) .Returns(Result.From(regularUser)); @@ -193,24 +195,4 @@ public class LibraryOwnershipPolicyTests // Assert Assert.False(result); } - - /// - /// Creates a library entity owned by . - /// - /// The Id of the user owning the library. - /// The created library entity. - private static LibraryEntity CreateLibrary(Guid ownerId) - { - return new LibraryEntity - { - Id = Guid.NewGuid(), - UserId = ownerId, - Title = "Test Library", - LibraryType = LibraryType.Book, - ContentLocations = [], - CreatedBy = ownerId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }; - } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs new file mode 100644 index 00000000..e21aec33 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Authorization/Policies/Over18/Over18PolicyTests.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Time; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Core.Authorization.Policies.Over18; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.Over18; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class Over18PolicyTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IUserRepository _mockUserRepository; + private readonly Over18Policy _sut; + private readonly UserEntityFixture _userEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public Over18PolicyTests() + { + _mockUnitOfWork = Substitute.For(); + _mockUserRepository = Substitute.For(); + _mockUnitOfWork.UserRepository.Returns(_mockUserRepository); + + _sut = new Over18Policy(_mockUnitOfWork, Substitute.For()); + } + + [Fact] + public async Task EvaluateAsync_WhenUserExists_ShouldReturnTrue() + { + // Arrange + UserEntity user = _userEntityFixture.Create(); + _mockUserRepository.GetByIdAsync(user.Id, Arg.Any()) + .Returns(Result.From(user)); + + // Act + bool result = await _sut.EvaluateAsync(user.Id, null, CancellationToken.None); + + // Assert + Assert.True(result); + } + + [Fact] + public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse() + { + // Arrange + Guid userId = Guid.NewGuid(); + _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task EvaluateAsync_WhenGetUserReturnsFailure_ShouldReturnFalse() + { + // Arrange + Guid userId = Guid.NewGuid(); + _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve user")); + + // Act + bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None); + + // Assert + Assert.False(result); + } + + [Fact] + public async Task EvaluateAsync_WhenUserEntityIsNull_ShouldReturnFalse() + { + // Arrange + Guid userId = Guid.NewGuid(); + _mockUserRepository.GetByIdAsync(userId, Arg.Any()) + .Returns(Result.Success(null)); + + // Act + bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None); + + // Assert + Assert.False(result); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTrackerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTrackerTests.cs new file mode 100644 index 00000000..547f3f97 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Cancellation/MediaLibrariesScanCancellationTrackerTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Cancellation; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibrariesScanCancellationTrackerTests +{ + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + [Fact] + public void GetTokenForScan_WhenScanWasRegistered_ShouldReturnActiveToken() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + sut.RegisterScan(compositeId); + CancellationToken token = sut.GetTokenForScan(compositeId); + + // Assert + Assert.False(token.IsCancellationRequested); + } + + [Fact] + public void GetTokenForScan_WhenScanWasNotRegistered_ShouldReturnNone() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + CancellationToken token = sut.GetTokenForScan(compositeId); + + // Assert + Assert.Equal(CancellationToken.None, token); + } + + [Fact] + public void CancelScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + sut.RegisterScan(compositeId); + CancellationToken token = sut.GetTokenForScan(compositeId); + + // Act + sut.CancelScan(compositeId); + + // Assert + Assert.True(token.IsCancellationRequested); + Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId)); + } + + [Fact] + public void RemoveScan_WhenScanWasRegistered_ShouldCancelItsTokenAndRemoveTheScan() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + sut.RegisterScan(compositeId); + CancellationToken token = sut.GetTokenForScan(compositeId); + + // Act + sut.RemoveScan(compositeId); + + // Assert + Assert.True(token.IsCancellationRequested); + Assert.Equal(CancellationToken.None, sut.GetTokenForScan(compositeId)); + } + + [Fact] + public void CancelScan_WhenScanWasNotRegistered_ShouldNotThrow() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + + // Act + Action act = () => sut.CancelScan(compositeId); + + // Assert + act(); + } + + [Fact] + public void Dispose_ShouldCancelAllRegisteredScans() + { + // Arrange + MediaLibrariesScanCancellationTracker sut = new(); + MediaLibraryScanCompositeId firstCompositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanCompositeId secondCompositeId = _mediaLibraryScanCompositeIdFixture.Create(); + sut.RegisterScan(firstCompositeId); + sut.RegisterScan(secondCompositeId); + CancellationToken firstToken = sut.GetTokenForScan(firstCompositeId); + CancellationToken secondToken = sut.GetTokenForScan(secondCompositeId); + + // Act + sut.Dispose(); + + // Assert + Assert.True(firstToken.IsCancellationRequested); + Assert.True(secondToken.IsCancellationRequested); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs new file mode 100644 index 00000000..7d107d7b --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanDiffJobTests.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanDiffJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MediaLibraryScanDiffJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanDiffJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanDiffJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenMarkingChangesSucceeds_ShouldCompleteAndPublishProgress() + { + // Arrange + _mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockStagingResultsRepository.Received(1).MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenMarkingChangesFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockStagingResultsRepository.MarkChangesAgainstSnapshotAsync(_scanId.Value, _libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to mark the changes against the snapshot")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs new file mode 100644 index 00000000..cc07e71a --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanHashJobTests.cs @@ -0,0 +1,173 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; +using Lumina.Application.Common.Infrastructure.Security; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanHashJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly IFileHashService _mockFileHashService; + private readonly MediaLibraryScanHashJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanHashJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _mockFileHashService = Substitute.For(); + _mockServiceProvider.GetService(typeof(IFileHashService)).Returns(_mockFileHashService); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanHashJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenFilesNeedHashing_ShouldHashAndPersistThemAndComplete() + { + // Arrange + List filesToHash = [_hashedFileSystemFileDtoFixture.Create(path: "/books/book1.pdf"), _hashedFileSystemFileDtoFixture.Create(path: "/books/book2.pdf")]; + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(2)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns( + Result.From>(filesToHash), + Result.From>([])); + _mockFileHashService.HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()) + .Returns(callInfo => Task.FromResult(callInfo.Arg>() + .Select(file => file with { CurrentHash = 42UL }) + .ToList())); + _mockStagingResultsRepository.UpdateFileHashesAsync(_scanId.Value, Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockFileHashService.Received(1).HashFilesAsync( + Arg.Any>(), + Arg.Any>(), + Arg.Any()); + await _mockStagingResultsRepository.Received(1).UpdateFileHashesAsync( + _scanId.Value, + Arg.Is>(files => files.Count == 2 && files.All(file => file.CurrentHash == 42UL)), + Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenNoFilesNeedHashing_ShouldCompleteWithoutHashing() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Result.From(0)); + _mockStagingResultsRepository.GetFilesToHashPageAsync(_scanId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockStagingResultsRepository.DidNotReceive().UpdateFileHashesAsync(Arg.Any(), Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCountingFilesFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockStagingResultsRepository.GetFilesToHashCountAsync(_scanId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to count the files to hash")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockFileHashService.DidNotReceive().HashFilesAsync(Arg.Any>(), Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } +} 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 new file mode 100644 index 00000000..63877702 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanMetadataEnrichmentJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly ILogger _mockLogger; + private readonly MediaLibraryScanMetadataEnrichmentJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanMetadataEnrichmentJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _mockLogger = Substitute.For>(); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanMetadataEnrichmentJob(_mockServiceScopeFactory, _mockLogger) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenNoBooksNeedEnrichment_ShouldCompleteAndPublishFinishedEvent() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(0)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the metadata provider configurations")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs new file mode 100644 index 00000000..1189a17c --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanResultsSaveJobTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanResultsSaveJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryScanSnapshotRepository _mockSnapshotRepository; + private readonly IBookRepository _mockBookRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly MediaLibraryScanResultsSaveJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanResultsSaveJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockSnapshotRepository = Substitute.For(); + _mockBookRepository = Substitute.For(); + _mockUnitOfWork.LibraryScanSnapshotRepository.Returns(_mockSnapshotRepository); + _mockUnitOfWork.BookRepository.Returns(_mockBookRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new MediaLibraryScanResultsSaveJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenScanResultsAreApplied_ShouldCreateShellBooksAndPublishFinishedEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>(["deleted.pdf"])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>(["book1.pdf", "book2.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + _mockBookRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.Path == "deleted.pdf"), Arg.Any()); + await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "book1.pdf" && book.Title == "book1" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any()); + await _mockBookRepository.Received(1).InsertAsync(Arg.Is(book => book.Path == "book2.pdf" && book.Title == "book2" && book.MetadataStatus == MetadataStatus.Pending), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenBookAlreadyExists_ShouldSkipInsertingIt() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockSnapshotRepository.ApplySnapshotSwapAsync(_libraryId.Value, _scanId.Value, _userId.Value, Arg.Any()) + .Returns(Result.From(Result.Updated)); + _mockSnapshotRepository.GetPathsAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>(["existing.pdf"])); + _mockBookRepository.GetByPathAsync(_libraryId.Value, "existing.pdf", Arg.Any()) + .Returns(Result.From(_bookEntityFixture.Create(path: "existing.pdf"))); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockBookRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingDeletedPathsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockSnapshotRepository.GetDeletedPathsAsync(_libraryId.Value, _scanId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to get the deleted paths")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs new file mode 100644 index 00000000..9b59314d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/ScanFailurePublisherTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanFailurePublisherTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScanFailurePublisherTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockDomainEventPublisher = Substitute.For(); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + } + + [Fact] + public async Task PublishAsync_WhenCalled_ShouldPublishLibraryScanFailedDomainEvent() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + Exception exception = new("The scan job failed"); + + // Act + await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, exception, CancellationToken.None); + + // Assert + await _mockDomainEventPublisher.Received(1).PublishAsync( + Arg.Is(domainEvent => + domainEvent.LibraryId == libraryId + && domainEvent.MediaLibraryScanCompositeId == compositeId + && domainEvent.ErrorMessage == "The scan job failed"), + Arg.Any()); + } + + [Fact] + public async Task PublishAsync_WhenPublisherThrows_ShouldNotThrow() + { + // Arrange + LibraryId libraryId = _libraryIdFixture.Create(); + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => new ValueTask(Task.FromException(new InvalidOperationException("Publishing failed")))); + + // Act + Exception? caughtException = null; + try + { + await ScanFailurePublisher.PublishAsync(_mockServiceScopeFactory, libraryId, compositeId, new Exception("boom"), CancellationToken.None); + } + catch (Exception exception) + { + caughtException = exception; + } + + // Assert + Assert.Null(caughtException); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs new file mode 100644 index 00000000..04b5f70f --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/WrittenContent/Books/BooksFileSystemDiscoveryJobTests.cs @@ -0,0 +1,223 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BooksFileSystemDiscoveryJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly ILibraryScanStagingResultsRepository _mockStagingResultsRepository; + private readonly IDirectoryScanFingerprintRepository _mockDirectoryScanFingerprintRepository; + private readonly IDomainEventPublisher _mockDomainEventPublisher; + private readonly BooksFileSystemDiscoveryJob _sut; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ScanId _scanId; + private readonly UserId _userId; + private readonly LibraryId _libraryId; + + /// + /// Initializes a new instance of the class. + /// + public BooksFileSystemDiscoveryJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockStagingResultsRepository = Substitute.For(); + _mockDirectoryScanFingerprintRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockUnitOfWork.LibraryScanStagingResultsRepository.Returns(_mockStagingResultsRepository); + _mockUnitOfWork.DirectoryScanFingerprintRepository.Returns(_mockDirectoryScanFingerprintRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockDomainEventPublisher = Substitute.For(); + _mockDomainEventPublisher.PublishAsync(Arg.Any(), Arg.Any()) + .Returns(ValueTask.CompletedTask); + _mockServiceProvider.GetService(typeof(IDomainEventPublisher)).Returns(_mockDomainEventPublisher); + + _scanId = _scanIdFixture.Create(); + _userId = _userIdFixture.Create(); + _libraryId = _libraryIdFixture.Create(); + _sut = new BooksFileSystemDiscoveryJob(_mockServiceScopeFactory) + { + ScanId = _scanId, + UserId = _userId, + LibraryId = _libraryId + }; + } + + [Fact] + public async Task ExecuteAsync_WhenContentLocationContainsBookFiles_ShouldDiscoverAndStageThemAndComplete() + { + // Arrange + using TemporaryLibraryDirectory temporaryLibraryDirectory = new(); + temporaryLibraryDirectory.CreateFile("book1.pdf", "book content"); + temporaryLibraryDirectory.CreateFile("notes.log", "not a book"); + string subdirectoryPath = temporaryLibraryDirectory.CreateSubdirectory("sub"); + File.WriteAllText(Path.Combine(subdirectoryPath, "book2.epub"), "another book content"); + + LibraryEntity libraryEntity = _libraryEntityFixture.Create( + id: _libraryId.Value, + userId: _userId.Value, + title: "Test Library", + libraryType: LibraryType.Book, + contentLocations: [temporaryLibraryDirectory.Path], + shouldSkipUnchangedDirectoriesDuringScan: false); + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(libraryEntity)); + _mockStagingResultsRepository.InsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Created)); + _mockDirectoryScanFingerprintRepository.UpsertRangeAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + IReadOnlyList? actualEntities = _mockStagingResultsRepository.ReceivedCalls() + .Where(call => call.GetMethodInfo().Name == nameof(ILibraryScanStagingResultsRepository.InsertRangeAsync)) + .Select(call => call.GetArguments().FirstOrDefault() as IReadOnlyList) + .FirstOrDefault(); + Assert.True(actualEntities is not null, $"InsertRangeAsync was not called. Received: {string.Join(", ", _mockStagingResultsRepository.ReceivedCalls().Select(call => call.GetMethodInfo().Name))}"); + Assert.Equal( + ["book1.pdf", "book2.epub"], + actualEntities!.Select(entity => Path.GetFileName(entity.Path)).OrderBy(name => name, StringComparer.Ordinal)); + await _mockDirectoryScanFingerprintRepository.DidNotReceive().UpsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenGettingTheLibraryFails_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the library")); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockStagingResultsRepository.DidNotReceive().InsertRangeAsync(Arg.Any>(), Arg.Any()); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId + && domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId + && domainEvent.MediaLibraryScanCompositeId.UserId == _userId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenLibraryDoesNotExist_ShouldMarkJobAsFailedAndPublishFailureEvent() + { + // Arrange + _mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Failed, _sut.Status); + await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => + domainEvent.LibraryId == _libraryId), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldMarkJobAsCanceledAndThrow() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task operation = _sut.ExecuteAsync(Guid.NewGuid(), new { }, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); + } + + /// + /// Test helper managing a temporary library directory, deleted when the test finishes. + /// + private sealed class TemporaryLibraryDirectory : IDisposable + { + private bool _disposed; + + public TemporaryLibraryDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-books-discovery-{Guid.NewGuid()}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void CreateFile(string fileName, string content) + { + File.WriteAllText(System.IO.Path.Combine(Path, fileName), content); + } + + public string CreateSubdirectory(string name) + { + string subdirectoryPath = System.IO.Path.Combine(Path, name); + Directory.CreateDirectory(subdirectoryPath); + return subdirectoryPath; + } + + public void Dispose() + { + if (!_disposed) + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the temporary library directory + } + _disposed = true; + } + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs new file mode 100644 index 00000000..1a5ff63f --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/DebouncedMediaLibraryScanProgressNotifierTests.cs @@ -0,0 +1,171 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; +using Microsoft.AspNetCore.SignalR; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DebouncedMediaLibraryScanProgressNotifierTests +{ + private readonly IHubContext _mockHubContext; + private readonly IHubClients _mockHubClients; + private readonly IClientProxy _mockClientProxy; + private readonly IMediaLibrariesScanProgressTracker _mockProgressTracker; + private readonly DebouncedMediaLibraryScanProgressNotifier _sut; + private readonly MediaLibraryScanCompositeIdFixture _mediaLibraryScanCompositeIdFixture = new(); + private readonly MediaLibraryScanProgressFixture _mediaLibraryScanProgressFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DebouncedMediaLibraryScanProgressNotifierTests() + { + _mockHubContext = Substitute.For>(); + _mockHubClients = Substitute.For(); + _mockClientProxy = Substitute.For(); + _mockHubContext.Clients.Returns(_mockHubClients); + _mockHubClients.Group(Arg.Any()).Returns(_mockClientProxy); + _mockClientProxy.SendCoreAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.CompletedTask); + + _mockProgressTracker = Substitute.For(); + _sut = new DebouncedMediaLibraryScanProgressNotifier(_mockHubContext, _mockProgressTracker); + } + + [Fact] + public async Task SendLibraryProgressUpdateEventAsync_WhenTokenIsCancelled_ShouldNotPublishOrQueryProgress() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + await _sut.SendLibraryProgressUpdateEventAsync(compositeId, cancellationTokenSource.Token); + + // Assert + _mockProgressTracker.DidNotReceive().GetScanProgress(Arg.Any()); + _mockHubClients.DidNotReceive().Group(Arg.Any()); + } + + [Fact] + public async Task SendLibraryProgressUpdateEventAsync_WhenProgressExists_ShouldSendProgressUpdateToGroup() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create( + scanId: compositeId.ScanId, + userId: compositeId.UserId, + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running); + _mockProgressTracker.GetScanProgress(compositeId).Returns(Result.From(progress)); + + // Act + await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + + // Assert + _mockHubClients.Received(1).Group(compositeId.ToString()); + await _mockClientProxy.Received(1).SendCoreAsync( + "libraryScanProgressUpdateEvent", + Arg.Is(args => args.Length == 1 + && args[0] != null + && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Running.ToString()), + Arg.Any()); + } + + [Fact] + public async Task SendLibraryProgressUpdateEventAsync_WhenProgressIsMissing_ShouldNotSendUpdate() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _mockProgressTracker.GetScanProgress(compositeId) + .Returns(Error.Failure("Tracking.Error", "The scan progress is missing")); + + // Act + await _sut.SendLibraryProgressUpdateEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenProgressExists_ShouldSendFinishedEventWithCompletedStatus() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create( + scanId: compositeId.ScanId, + userId: compositeId.UserId, + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running); + _mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress)); + + // Act + await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.Received(1).SendCoreAsync( + "libraryScanFinishedEvent", + Arg.Is(args => args.Length == 1 + && args[0] != null + && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Completed.ToString()), + Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFinishedEventAsync_WhenProgressIsMissing_ShouldNotSendFinishedEvent() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + _mockProgressTracker.RemoveScanProgress(compositeId) + .Returns(Error.Failure("Tracking.Error", "The scan progress is missing")); + + // Act + await _sut.SendLibraryScanFinishedEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.DidNotReceive().SendCoreAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SendLibraryScanFailedEventAsync_WhenProgressExists_ShouldSendFailedEventWithFailedStatus() + { + // Arrange + MediaLibraryScanCompositeId compositeId = _mediaLibraryScanCompositeIdFixture.Create(); + MediaLibraryScanProgress progress = _mediaLibraryScanProgressFixture.Create( + scanId: compositeId.ScanId, + userId: compositeId.UserId, + completedJobs: 1, + totalJobs: 2, + status: LibraryScanJobStatus.Running); + _mockProgressTracker.RemoveScanProgress(compositeId).Returns(Result.From(progress)); + + // Act + await _sut.SendLibraryScanFailedEventAsync(compositeId, CancellationToken.None); + + // Assert + await _mockClientProxy.Received(1).SendCoreAsync( + "libraryScanFailedEvent", + Arg.Is(args => args.Length == 1 + && args[0] != null + && ((MediaLibraryScanProgressResponse)args[0]!).Status == LibraryScanJobStatus.Failed.ToString()), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs new file mode 100644 index 00000000..89c3566d --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Progress/MediaLibraryScanProgressHubTests.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; +using Microsoft.AspNetCore.SignalR; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Progress; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanProgressHubTests +{ + [Fact] + public async Task SubscribeToScan_WhenCalled_ShouldAddTheConnectionToTheScanGroup() + { + // Arrange + MediaLibraryScanProgressHub sut = new(); + HubCallerContext context = Substitute.For(); + context.ConnectionId.Returns("connection-1"); + IGroupManager groupManager = Substitute.For(); + sut.Context = context; + sut.Groups = groupManager; + Guid scanId = Guid.NewGuid(); + Guid userId = Guid.NewGuid(); + + // Act + await sut.SubscribeToScan(scanId, userId); + + // Assert + await groupManager.Received(1).AddToGroupAsync("connection-1", $"{scanId}-{userId}", CancellationToken.None); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs new file mode 100644 index 00000000..9819f68a --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibrariesScanQueueTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibrariesScanQueueTests +{ + private readonly MediaLibrariesScanQueue _sut = new(); + + [Fact] + public async Task Writer_WhenJobIsWritten_ShouldAllowReadingItFromReader() + { + // Arrange + IMediaLibraryScanJob job = Substitute.For(); + + // Act + bool writeResult = _sut.Writer.TryWrite(job); + IMediaLibraryScanJob readJob = await _sut.Reader.ReadAsync(CancellationToken.None); + + // Assert + Assert.True(writeResult); + Assert.Same(job, readJob); + } + + [Fact] + public async Task Writer_WhenMultipleJobsAreWritten_ShouldReadThemInFifoOrder() + { + // Arrange + IMediaLibraryScanJob firstJob = Substitute.For(); + IMediaLibraryScanJob secondJob = Substitute.For(); + + // Act + _sut.Writer.TryWrite(firstJob); + _sut.Writer.TryWrite(secondJob); + IMediaLibraryScanJob firstReadJob = await _sut.Reader.ReadAsync(CancellationToken.None); + IMediaLibraryScanJob secondReadJob = await _sut.Reader.ReadAsync(CancellationToken.None); + + // Assert + Assert.Same(firstJob, firstReadJob); + Assert.Same(secondJob, secondReadJob); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs new file mode 100644 index 00000000..14c8da73 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Queue/MediaLibraryScanJobProcessorJobTests.cs @@ -0,0 +1,146 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; +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.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +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.MediaLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Queue; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryScanJobProcessorJobTests +{ + private readonly IMediaLibrariesScanCancellationTracker _mockCancellationTracker; + private readonly ScanIdFixture _scanIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly LibraryIdFixture _libraryIdFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryScanJobProcessorJobTests() + { + _mockCancellationTracker = Substitute.For(); + } + + [Fact] + public async Task StartAsync_WhenJobIsEnqueued_ShouldExecuteTheJobWithLinkedCancellationToken() + { + // Arrange + MediaLibrariesScanQueue queue = new(); + MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker); + RecordingScanJob job = CreateRecordingScanJob(); + _mockCancellationTracker.GetTokenForScan(Arg.Any()) + .Returns(CancellationToken.None); + + await sut.StartAsync(CancellationToken.None); + + // Act + queue.Writer.TryWrite(job); + await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5)); + + // Assert + Assert.True(job.WasExecuted); + Assert.False(job.ReceivedCancellationToken.IsCancellationRequested); + _mockCancellationTracker.Received(1).GetTokenForScan( + Arg.Is(compositeId => compositeId.ScanId == job.ScanId && compositeId.UserId == job.UserId)); + + await sut.StopAsync(CancellationToken.None); + } + + [Fact] + public async Task StartAsync_WhenScanWasAlreadyCancelled_ShouldExecuteJobWithAlreadyCancelledLinkedToken() + { + // Arrange + MediaLibrariesScanQueue queue = new(); + MediaLibraryScanJobProcessorJob sut = new(queue, _mockCancellationTracker); + RecordingScanJob job = CreateRecordingScanJob(); + using CancellationTokenSource scanCancellationTokenSource = new(); + scanCancellationTokenSource.Cancel(); + _mockCancellationTracker.GetTokenForScan(Arg.Any()) + .Returns(scanCancellationTokenSource.Token); + + await sut.StartAsync(CancellationToken.None); + + // Act + queue.Writer.TryWrite(job); + await job.ExecutedTask.WaitAsync(TimeSpan.FromSeconds(5)); + + // Assert + Assert.True(job.WasExecuted); + Assert.True(job.ReceivedCancellationToken.IsCancellationRequested); + + await sut.StopAsync(CancellationToken.None); + } + + /// + /// Creates a recording scan job with a random scan and user identity. + /// + /// The created recording scan job. + private RecordingScanJob CreateRecordingScanJob() + { + return new RecordingScanJob + { + ScanId = _scanIdFixture.Create(), + UserId = _userIdFixture.Create(), + LibraryId = _libraryIdFixture.Create() + }; + } + + /// + /// Test double for that records the token it was executed with. + /// + private sealed class RecordingScanJob : IMediaLibraryScanJob + { + private readonly TaskCompletionSource _executed = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public required ScanId ScanId { get; set; } + + public required UserId UserId { get; set; } + + public required LibraryId LibraryId { get; set; } + + public List Children { get; } = []; + + public List Parents { get; } = []; + + public LibraryScanJobStatus Status { get; private set; } + + public Task ExecutedTask => _executed.Task; + + public bool WasExecuted { get; private set; } + + public CancellationToken ReceivedCancellationToken { get; private set; } + + public void AddChild(IMediaLibraryScanJob job) + { + } + + public void AddParent(IMediaLibraryScanJob job) + { + } + + public Task ExecuteAsync(Guid id, TInput input, CancellationToken cancellationToken) + { + WasExecuted = true; + ReceivedCancellationToken = cancellationToken; + _executed.TrySetResult(true); + return Task.CompletedTask; + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs new file mode 100644 index 00000000..723a1fe2 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -0,0 +1,166 @@ +#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.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginDetectionSyncJobTests +{ + private readonly IServiceScopeFactory _mockServiceScopeFactory; + private readonly IServiceScope _mockServiceScope; + private readonly IServiceProvider _mockServiceProvider; + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly IPluginManager _mockPluginManager; + private readonly ILogger _mockLogger; + + /// + /// Initializes a new instance of the class. + /// + public PluginDetectionSyncJobTests() + { + _mockServiceScopeFactory = Substitute.For(); + _mockServiceScope = Substitute.For(); + _mockServiceProvider = Substitute.For(); + _mockServiceScopeFactory.CreateScope().Returns(_mockServiceScope); + _mockServiceScope.ServiceProvider.Returns(_mockServiceProvider); + + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + + _mockPluginManager = Substitute.For(); + _mockLogger = Substitute.For>(); + } + + [Fact] + public async Task StartAsync_WhenPluginsAreLoaded_ShouldPersistTheDetectionOfAllPlugins() + { + // Arrange + IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin", new Version(1, 2, 3)); + IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin", new Version(2, 0, 0)); + _mockPluginManager.GetPlugins().Returns([firstPlugin, secondPlugin]); + _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + PluginDetectionSyncJob sut = CreateSut(); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockPluginRepository.Received(1).UpsertAsync( + Arg.Is(plugin => plugin.Id == firstPlugin.Id + && plugin.Name == firstPlugin.Name + && plugin.Author == firstPlugin.Author + && plugin.Version == firstPlugin.Version.ToString() + && plugin.Description == firstPlugin.Description + && plugin.LoadStatus == PluginLoadStatus.Loaded), + Arg.Any()); + await _mockPluginRepository.Received(1).UpsertAsync( + Arg.Is(plugin => plugin.Id == secondPlugin.Id + && plugin.Name == secondPlugin.Name + && plugin.LoadStatus == PluginLoadStatus.Loaded), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenUpsertFails_ShouldLogErrorAndContinueWithOtherPlugins() + { + // Arrange + IPlugin failingPlugin = CreatePlugin(Guid.NewGuid(), "Failing Plugin", new Version(1, 0, 0)); + IPlugin successfulPlugin = CreatePlugin(Guid.NewGuid(), "Successful Plugin", new Version(1, 0, 0)); + _mockPluginManager.GetPlugins().Returns([failingPlugin, successfulPlugin]); + _mockPluginRepository.UpsertAsync( + Arg.Is(plugin => plugin.Id == failingPlugin.Id), + Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to persist the plugin")); + _mockPluginRepository.UpsertAsync( + Arg.Is(plugin => plugin.Id == successfulPlugin.Id), + Arg.Any()) + .Returns(Result.From(Result.Updated)); + PluginDetectionSyncJob sut = CreateSut(); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockPluginRepository.Received(1).UpsertAsync(Arg.Is(plugin => plugin.Id == successfulPlugin.Id), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges() + { + // Arrange + _mockPluginManager.GetPlugins().Returns([]); + PluginDetectionSyncJob sut = CreateSut(); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockPluginRepository.DidNotReceiveWithAnyArgs().UpsertAsync(default!, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + /// + /// Invokes the protected of the job and awaits its completion. + /// + /// The job to execute. + private static async Task StartAndWaitForExecutionAsync(PluginDetectionSyncJob sut) + { + MethodInfo executeAsyncMethod = typeof(PluginDetectionSyncJob).GetMethod("ExecuteAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; + Task executingTask = (Task)executeAsyncMethod.Invoke(sut, [CancellationToken.None])!; + await executingTask; + } + + /// + /// Creates the system under test wired to the mocked dependencies. + /// + /// The created job instance. + private PluginDetectionSyncJob CreateSut() + { + return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, [], _mockLogger); + } + + /// + /// Creates a mocked plugin with the provided identity. + /// + /// The Id of the plugin. + /// The name of the plugin. + /// The version of the plugin. + /// The created plugin mock. + private static IPlugin CreatePlugin(Guid id, string name, Version version) + { + IPlugin plugin = Substitute.For(); + plugin.Id.Returns(id); + plugin.Name.Returns(name); + plugin.Author.Returns("Test Author"); + plugin.Version.Returns(version); + plugin.Description.Returns("Test plugin description"); + return plugin; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs new file mode 100644 index 00000000..4a1d9810 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoadContextTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.Plugins; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Reflection; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginLoadContextTests +{ + [Fact] + public void LoadFromAssemblyName_WhenAssemblyIsResolvableFromDefaultContext_ShouldReturnTheSharedAssembly() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + + // Act + Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName()); + + // Assert + Assert.NotNull(result); + Assert.Equal(typeof(object).Assembly.GetName().Name, result.GetName().Name); + } + + [Fact] + public void Load_WhenAssemblyExistsOnlyInPluginDirectory_ShouldLoadItFromThePluginDirectory() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"), "PluginLocalDependency.dll"); + PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!; + + // Act + Assembly? result = (Assembly?)loadMethod.Invoke(sut, [new AssemblyName("PluginLocalDependency")]); + + // Assert + Assert.NotNull(result); + Assert.Equal("Lumina.TestPlugin", result!.GetName().Name); + Assert.Equal(destinationPath, result.Location); + } + + [Fact] + public void LoadFromAssemblyName_WhenAssemblyIsNotFoundAnywhere_ShouldThrowFileNotFoundException() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context"); + + // Act + Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}")); + + // Assert + Assert.Throws(act); + } + + /// + /// Test helper managing a temporary plugins directory, deleted when the test finishes. + /// + private sealed class TemporaryPluginDirectory : IDisposable + { + private bool _disposed; + + public TemporaryPluginDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-load-context-{Guid.NewGuid()}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public string CopyDll(string sourceDllPath, string destinationFileName) + { + string destinationPath = System.IO.Path.Combine(Path, destinationFileName); + File.Copy(sourceDllPath, destinationPath); + return destinationPath; + } + + public void Dispose() + { + if (!_disposed) + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the temporary plugins directory + } + catch (UnauthorizedAccessException) + { + // the plugin assemblies are still locked by their load contexts, best effort cleanup only + } + _disposed = true; + } + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs new file mode 100644 index 00000000..84dcff66 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginLoaderTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Common.Models.DTO.Plugins; +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginLoaderTests +{ + [Fact] + public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors() + { + // Arrange + string nonExistentDirectory = Path.Combine(Path.GetTempPath(), $"lumina-plugins-{Guid.NewGuid()}"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services); + + // Assert + Assert.Empty(result.Plugins); + Assert.Empty(result.Errors); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsInvalidAssembly_ShouldRecordError() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CreateFile("invalid.dll", "this is not a valid assembly"); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + string error = Assert.Single(result.Errors); + Assert.Contains("invalid.dll", error); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(typeof(IPlugin).Assembly.Location); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + Assert.Empty(result.Plugins); + Assert.Empty(result.Errors); + } + + [Fact] + public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldLoadPluginAndRegisterItsServices() + { + // Arrange + using TemporaryPluginDirectory temporaryPluginDirectory = new(); + temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); + IServiceCollection services = new ServiceCollection(); + + // Act + PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services); + + // Assert + IPlugin loadedPlugin = Assert.Single(result.Plugins); + Assert.Empty(result.Errors); + Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); + Assert.Equal("Test Plugin", loadedPlugin.Name); + Assert.Contains(services, descriptor => descriptor.ImplementationInstance as string == "plugin-services-registered"); + } + + /// + /// Gets the path of the Lumina.TestPlugin assembly from the test output directory. + /// The assembly is referenced by the test project but no type from it is used, so it is not loaded + /// into the default load context, which is what makes the plugin loading pipeline testable. + /// + /// The path of the test plugin assembly. + private static string GetTestPluginAssemblyPath() + { + return Path.Combine(AppContext.BaseDirectory, "Lumina.TestPlugin.dll"); + } + + /// + /// Test helper managing a temporary plugins directory, deleted when the test finishes. + /// + private sealed class TemporaryPluginDirectory : IDisposable + { + private bool _disposed; + + public TemporaryPluginDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-plugin-loader-{Guid.NewGuid()}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void CreateFile(string fileName, string content) + { + File.WriteAllText(System.IO.Path.Combine(Path, fileName), content); + } + + public void CopyDll(string sourceDllPath) + { + File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath))); + } + + public void Dispose() + { + if (!_disposed) + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the temporary plugins directory + } + catch (UnauthorizedAccessException) + { + // the plugin assemblies are still locked by their load contexts, best effort cleanup only + } + _disposed = true; + } + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs new file mode 100644 index 00000000..e20be5f7 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginManagerTests.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Plugins; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginManagerTests +{ + [Fact] + public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins() + { + // Arrange + IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin"); + IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin"); + PluginManager sut = new([firstPlugin, secondPlugin]); + + // Act + IReadOnlyList result = sut.GetPlugins(); + + // Assert + Assert.Equal(2, result.Count); + Assert.Contains(firstPlugin, result); + Assert.Contains(secondPlugin, result); + } + + [Fact] + public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList() + { + // Arrange + PluginManager sut = new([]); + + // Act + IReadOnlyList result = sut.GetPlugins(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void GetPlugin_WhenPluginWithIdWasLoaded_ShouldReturnThePlugin() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin"); + PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")]); + + // Act + IPlugin? result = sut.GetPlugin(pluginId); + + // Assert + Assert.Same(expectedPlugin, result); + } + + [Fact] + public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull() + { + // Arrange + PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")]); + + // Act + IPlugin? result = sut.GetPlugin(Guid.NewGuid()); + + // Assert + Assert.Null(result); + } + + /// + /// Creates a mocked plugin with the provided identity. + /// + /// The Id of the plugin. + /// The name of the plugin. + /// The created plugin mock. + private static IPlugin CreatePlugin(Guid id, string name) + { + IPlugin plugin = Substitute.For(); + plugin.Id.Returns(id); + plugin.Name.Returns(name); + return plugin; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs new file mode 100644 index 00000000..a56dcc62 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginSettingsStoreTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Domain.Common.Primitives; +using Lumina.Infrastructure.Core.Plugins; +using Microsoft.Extensions.Logging; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingsStoreTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IPluginRepository _mockPluginRepository; + private readonly ILogger _mockLogger; + private readonly PluginSettingsStore _sut; + + /// + /// Initializes a new instance of the class. + /// + public PluginSettingsStoreTests() + { + _mockUnitOfWork = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockLogger = Substitute.For>(); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + + _sut = new PluginSettingsStore(_mockUnitOfWork, _mockLogger); + } + + [Fact] + public async Task GetSettingsAsync_WhenPluginHasPersistedSettings_ShouldReturnDeserializedSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + Dictionary expectedSettings = new() { ["ApiKey"] = "test-key", ["Enabled"] = "true" }; + PluginEntity pluginEntity = CreatePluginEntity(pluginId, JsonSerializer.Serialize(expectedSettings)); + _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + .Returns(Result.From(pluginEntity)); + + // Act + IReadOnlyDictionary? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(expectedSettings, result); + } + + [Fact] + public async Task GetSettingsAsync_WhenPluginHasNoPersistedSettings_ShouldReturnNull() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + PluginEntity pluginEntity = CreatePluginEntity(pluginId, settingsJson: null); + _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + .Returns(Result.From(pluginEntity)); + + // Act + IReadOnlyDictionary? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSettingsAsync_WhenPluginDoesNotExist_ShouldReturnNull() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + IReadOnlyDictionary? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSettingsAsync_WhenRepositoryReturnsFailure_ShouldReturnNullAndLogWarning() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockPluginRepository.GetByIdAsync(pluginId, Arg.Any()) + .Returns(Error.Failure("Database.Error", "Failed to retrieve the plugin")); + + // Act + IReadOnlyDictionary? result = await _sut.GetSettingsAsync(pluginId, CancellationToken.None); + + // 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.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs new file mode 100644 index 00000000..0b32baa0 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Security/FileHashServiceTests.cs @@ -0,0 +1,185 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.MediaLibraryScanJobPayloads; +using Lumina.Infrastructure.Core.Security; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.IO.Hashing; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Security; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class FileHashServiceTests +{ + private readonly FileHashService _sut = new(); + private readonly HashedFileSystemFileDtoFixture _hashedFileSystemFileDtoFixture = new(); + + [Fact] + public async Task HashFilesAsync_WhenCalledWithFiles_ShouldInvokeCallbackAndComputeHashes() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath1 = temporaryTestDirectory.CreateFile("book1.pdf", "content of the first book"); + string filePath2 = temporaryTestDirectory.CreateFile("book2.pdf", "content of the second book"); + List inputFiles = + [ + _hashedFileSystemFileDtoFixture.Create(path: filePath1, size: new FileInfo(filePath1).Length, currentHash: 0, oldHash: 0, ticks: 0), + _hashedFileSystemFileDtoFixture.Create(path: filePath2, size: new FileInfo(filePath2).Length, currentHash: 0, oldHash: 0, ticks: 0) + ]; + int callbackInvocationCount = 0; + + // Act + List result = await _sut.HashFilesAsync( + inputFiles, + () => + { + callbackInvocationCount++; + return Task.CompletedTask; + }, + CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(2, callbackInvocationCount); + Assert.All(result, file => Assert.NotEqual(0UL, file.CurrentHash)); + // the hashing is parallelized, so the results are not guaranteed to be in the input order + Assert.Equal( + inputFiles.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal), + result.Select(file => file.Path).OrderBy(path => path, StringComparer.Ordinal)); + } + + [Fact] + public async Task HashFilesAsync_WhenFileIsEmpty_ShouldUseEmptyFileHash() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("empty.pdf", string.Empty); + List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; + + // Act + List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + + // Assert + HashedFileSystemFileDto hashedFile = Assert.Single(result); + Assert.Equal(filePath, hashedFile.Path); + Assert.Equal(BitConverter.ToUInt64(new XxHash64().GetCurrentHash()), hashedFile.CurrentHash); + } + + [Fact] + public async Task HashFilesAsync_WhenFileContentChanges_ShouldProduceDifferentHashes() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("book.pdf", "original content"); + List firstInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; + + // Act + List firstResult = await _sut.HashFilesAsync(firstInputFiles, () => Task.CompletedTask, CancellationToken.None); + await File.WriteAllTextAsync(filePath, "changed content"); + List secondInputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; + List secondResult = await _sut.HashFilesAsync(secondInputFiles, () => Task.CompletedTask, CancellationToken.None); + + // Assert + Assert.NotEqual(firstResult[0].CurrentHash, secondResult[0].CurrentHash); + } + + [Fact] + public async Task HashFilesAsync_WhenFileDoesNotExist_ShouldSkipFileAndNotThrow() + { + // Arrange + string nonExistentFilePath = Path.Combine(Path.GetTempPath(), "does-not-exist.pdf"); + List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: nonExistentFilePath, size: 100, currentHash: 0, oldHash: 0, ticks: 0)]; + + // Act + List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task HashFilesAsync_WhenOneFileIsMissing_ShouldHashTheExistingFilesOnly() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string existingFilePath = temporaryTestDirectory.CreateFile("book.pdf", "content"); + List inputFiles = + [ + _hashedFileSystemFileDtoFixture.Create(path: existingFilePath, size: new FileInfo(existingFilePath).Length, currentHash: 0, oldHash: 0, ticks: 0), + _hashedFileSystemFileDtoFixture.Create(path: Path.Combine(temporaryTestDirectory.Path, "missing.pdf"), size: 100, currentHash: 0, oldHash: 0, ticks: 0) + ]; + + // Act + List result = await _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, CancellationToken.None); + + // Assert + HashedFileSystemFileDto hashedFile = Assert.Single(result); + Assert.Equal(existingFilePath, hashedFile.Path); + Assert.NotEqual(0UL, hashedFile.CurrentHash); + } + + [Fact] + public async Task HashFilesAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + using TemporaryTestDirectory temporaryTestDirectory = new(); + string filePath = temporaryTestDirectory.CreateFile("book.pdf", "content"); + List inputFiles = [_hashedFileSystemFileDtoFixture.Create(path: filePath, size: new FileInfo(filePath).Length, currentHash: 0, oldHash: 0, ticks: 0)]; + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task> operation = _sut.HashFilesAsync(inputFiles, () => Task.CompletedTask, cancellationTokenSource.Token); + + // Assert + await Assert.ThrowsAnyAsync(() => operation); + } + + /// + /// Test helper managing a temporary directory, deleted when the test finishes. + /// + private sealed class TemporaryTestDirectory : IDisposable + { + private bool _disposed; + + public TemporaryTestDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"lumina-file-hash-tests-{Guid.NewGuid()}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public string CreateFile(string fileName, string content) + { + string filePath = System.IO.Path.Combine(Path, fileName); + File.WriteAllText(filePath, content); + return filePath; + } + + public void Dispose() + { + if (!_disposed) + { + try + { + Directory.Delete(Path, recursive: true); + } + catch (IOException) + { + // best effort cleanup of the temporary test directory + } + _disposed = true; + } + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Time/DateTimeProviderTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Time/DateTimeProviderTests.cs new file mode 100644 index 00000000..0a9e54f8 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Time/DateTimeProviderTests.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Infrastructure.Core.Time; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Time; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DateTimeProviderTests +{ + private readonly DateTimeProvider _sut = new(); + + [Fact] + public void UtcNow_WhenCalled_ShouldReturnCurrentUtcTime() + { + // Arrange + DateTime before = DateTime.UtcNow; + + // Act + DateTime result = _sut.UtcNow; + + // Assert + DateTime after = DateTime.UtcNow; + Assert.True(result >= before && result <= after); + } + + [Fact] + public void UtcNow_WhenCalled_ShouldReturnUtcKind() + { + // Act + DateTime result = _sut.UtcNow; + + // Assert + Assert.Equal(DateTimeKind.Utc, result.Kind); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 383df266..ff7fd144 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -24,6 +24,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -40,7 +41,10 @@ + + + diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs new file mode 100644 index 00000000..5d27a75e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Common/Models/DTO/Settings/PluginSettingDescriptorDtoTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Contracts.UnitTests.Common.Models.DTO.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingDescriptorDtoTests +{ + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); + + [Fact] + public void Create_WhenConstructedWithValues_ShouldPreserveAllValues() + { + // Arrange + IReadOnlyList allowedValues = ["Fiction", "Non-Fiction"]; + + // Act + PluginSettingDescriptorDto result = _pluginSettingDescriptorDtoFixture.Create( + key: "Theme", + label: "Theme", + type: PluginSettingType.Select, + defaultValue: "Fiction", + allowedValues: allowedValues); + + // Assert + Assert.Equal("Theme", result.Key); + Assert.Equal("Theme", result.Label); + Assert.Equal(PluginSettingType.Select, result.Type); + Assert.Equal("Fiction", result.DefaultValue); + Assert.Same(allowedValues, result.AllowedValues); + } + + [Fact] + public void Create_WhenDefaultValuesAreNotProvided_ShouldDefaultToNull() + { + // Act + PluginSettingDescriptorDto result = _pluginSettingDescriptorDtoFixture.Create(defaultValue: null, allowedValues: null); + + // Assert + Assert.Null(result.DefaultValue); + Assert.Null(result.AllowedValues); + } + + [Fact] + public void Equality_WhenTwoDescriptorsHaveTheSameValues_ShouldBeEqual() + { + // Arrange + IReadOnlyList allowedValues = ["A"]; + + // Act + PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: allowedValues); + PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: allowedValues); + bool result = first == second; + + // Assert + Assert.True(result); + Assert.Equal(first, second); + Assert.Equal(first.GetHashCode(), second.GetHashCode()); + } + + [Fact] + public void Equality_WhenDescriptorsHaveDifferentAllowedValueInstances_ShouldNotBeEqual() + { + // Arrange + PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: ["A"]); + PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "Key", label: "Label", type: PluginSettingType.Text, defaultValue: "value", allowedValues: ["A"]); + + // Act + bool result = first == second; + + // Assert + Assert.False(result); + } + + [Fact] + public void Equality_WhenTwoDescriptorsHaveDifferentKeys_ShouldNotBeEqual() + { + // Arrange + PluginSettingDescriptorDto first = _pluginSettingDescriptorDtoFixture.Create(key: "KeyOne", label: "Label", type: PluginSettingType.Text); + PluginSettingDescriptorDto second = _pluginSettingDescriptorDtoFixture.Create(key: "KeyTwo", label: "Label", type: PluginSettingType.Text); + + // Act + bool result = first == second; + + // Assert + Assert.False(result); + Assert.NotEqual(first, second); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs new file mode 100644 index 00000000..51d25183 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IRemoteMetadataProviderGenericTests.cs @@ -0,0 +1,161 @@ +#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.Contracts.Core.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; + +/// +/// Contains unit tests for the interface. +/// +[ExcludeFromCodeCoverage] +public class IRemoteMetadataProviderGenericTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + + [Fact] + public async Task GetSearchResultsAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false); + TestBookMetadataProvider provider = new(expectedMetadata); + IRemoteMetadataProvider baseProvider = provider; + + // Act + IReadOnlyList result = await baseProvider.GetSearchResultsAsync(lookup, cancellationToken); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal(expectedMetadata, metadata); + Assert.Same(lookup, provider.ReceivedLookup); + Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); + } + + [Fact] + public async Task GetMetadataAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + BookMetadataDto expectedMetadata = _bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false); + TestBookMetadataProvider provider = new(expectedMetadata); + IRemoteMetadataProvider baseProvider = provider; + + // Act + MetadataDto? result = await baseProvider.GetMetadataAsync(lookup, cancellationToken); + + // Assert + Assert.Equal(expectedMetadata, Assert.IsType(result)); + Assert.Same(lookup, provider.ReceivedLookup); + Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + { + // Arrange + MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Search Result", includeOptionalProperties: false)); + IRemoteMetadataProvider baseProvider = provider; + + // Act + async Task Act() + { + await baseProvider.GetSearchResultsAsync(otherLookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Null(provider.ReceivedLookup); + } + + [Fact] + public async Task GetMetadataAsync_WhenLookupIsOfAnotherRuntimeType_ShouldThrowInvalidCastException() + { + // Arrange + MetadataLookupDto otherLookup = new OtherMetadataLookupDto(); + TestBookMetadataProvider provider = new(_bookMetadataDtoFixture.Create(title: "Exact Result", includeOptionalProperties: false)); + IRemoteMetadataProvider baseProvider = provider; + + // Act + async Task Act() + { + await baseProvider.GetMetadataAsync(otherLookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Null(provider.ReceivedLookup); + } + + /// + /// Test double for the typed metadata provider interface that records the forwarded arguments. + /// + [ExcludeFromCodeCoverage] + private sealed class TestBookMetadataProvider : IRemoteMetadataProvider + { + private readonly BookMetadataDto _metadata; + + /// + /// 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 metadata returned by the typed implementation. + public TestBookMetadataProvider(BookMetadataDto metadata) + { + _metadata = metadata; + } + + /// + public string Name => "Test Provider"; + + /// + public LibraryType SupportedLibraryType => LibraryType.Book; + + /// + public bool RequiresWebAccess => false; + + /// + public Task> GetSearchResultsAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ReceivedLookup = lookup; + ReceivedCancellationToken = cancellationToken; + return Task.FromResult>([_metadata]); + } + + /// + public Task GetMetadataAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ReceivedLookup = lookup; + ReceivedCancellationToken = cancellationToken; + 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.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj new file mode 100644 index 00000000..c7058532 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Lumina.Plugins.Contracts.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + 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.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs new file mode 100644 index 00000000..7e00dc7a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/DependencyInjection/OpenLibraryServicesTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.OpenLibrary.Common.DependencyInjection; +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using Lumina.Plugins.OpenLibrary.Core.Api; +using Lumina.Plugins.OpenLibrary.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibraryServicesTests +{ + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenCalled_ShouldRegisterTheMetadataProviderForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenCalled_ShouldRegisterTheOpenLibraryHttpClient() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenSettingsCallbackIsProvided_ShouldApplyTheCallbackToTheRuntimeSettings() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddOpenLibraryBookMetadataProvider( + pluginId: Guid.NewGuid(), + settingsCallback: settings => settings.ContactEmail = "callback@example.com"); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + Assert.Equal("callback@example.com", settings.ContactEmail); + Assert.Equal(10, settings.SearchResultLimit); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenASettingsStoreIsRegistered_ShouldApplyTheStoredSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + IPluginSettingsStore settingsStore = Substitute.For(); + settingsStore.GetSettingsAsync(pluginId, Arg.Any()) + .Returns(new Dictionary + { + [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "25" + }); + ServiceCollection services = new(); + services.AddSingleton(settingsStore); + + // Act + services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + Assert.Equal(25, settings.SearchResultLimit); + Assert.Equal(50, settings.WorkEditionLimit); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenTheSettingsStoreReturnsNull_ShouldKeepTheDefaultSettings() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + IPluginSettingsStore settingsStore = Substitute.For(); + settingsStore.GetSettingsAsync(pluginId, Arg.Any()) + .Returns((IReadOnlyDictionary?)null); + ServiceCollection services = new(); + services.AddSingleton(settingsStore); + + // Act + services.AddOpenLibraryBookMetadataProvider(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + OpenLibrarySettingsDto settings = serviceProvider.GetRequiredService(); + Assert.Equal(10, settings.SearchResultLimit); + Assert.Equal(50, settings.WorkEditionLimit); + } + + [Fact] + public void AddOpenLibraryBookMetadataProvider_WhenResolvedAcrossScopes_ShouldReturnDistinctRuntimeSettingsInstances() + { + // Arrange + ServiceCollection services = new(); + services.AddOpenLibraryBookMetadataProvider(pluginId: Guid.NewGuid()); + 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(); + + // Assert + Assert.NotSame(first, second); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs new file mode 100644 index 00000000..ef81ed0e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Common/Models/DTO/Settings/OpenLibrarySettingsDtoTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Common.Models.DTO.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibrarySettingsDtoTests +{ + [Fact] + public void Defaults_WhenCreated_ShouldUseTheDocumentedDefaultValues() + { + // Arrange + OpenLibrarySettingsDto sut = new(); + + // Act + + // Assert + Assert.Equal("Lumina-OpenLibrary/1.0", sut.UserAgent); + Assert.Null(sut.ContactEmail); + Assert.Equal(10, sut.SearchResultLimit); + Assert.Equal(50, sut.WorkEditionLimit); + Assert.Equal(TimeSpan.FromSeconds(1.1), sut.MinimumRequestInterval); + } + + [Fact] + public void Setters_WhenAssigned_ShouldExposeTheAssignedValues() + { + // Arrange + OpenLibrarySettingsDto sut = new(); + TimeSpan expectedInterval = TimeSpan.FromSeconds(3); + + // Act + sut.UserAgent = "CustomAgent/2.0"; + sut.ContactEmail = "contact@example.com"; + sut.SearchResultLimit = 15; + sut.WorkEditionLimit = 60; + sut.MinimumRequestInterval = expectedInterval; + + // Assert + Assert.Equal("CustomAgent/2.0", sut.UserAgent); + Assert.Equal("contact@example.com", sut.ContactEmail); + Assert.Equal(15, sut.SearchResultLimit); + Assert.Equal(60, sut.WorkEditionLimit); + Assert.Equal(expectedInterval, sut.MinimumRequestInterval); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs new file mode 100644 index 00000000..e06b5a33 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Api/OpenLibraryHttpClientTests.cs @@ -0,0 +1,549 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.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.Api; +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; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibraryHttpClientTests +{ + private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + + [Fact] + public void Constructor_WhenHttpClientHasNoBaseAddress_ShouldSetTheDefaultOpenLibraryBaseAddress() + { + // Arrange + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + + // Act + _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); + + // Assert + Assert.Equal(new Uri("https://openlibrary.org/"), httpClient.BaseAddress); + } + + [Fact] + public void Constructor_WhenHttpClientAlreadyHasBaseAddress_ShouldKeepTheExistingBaseAddress() + { + // Arrange + Uri existingBaseAddress = new("https://example.com/"); + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()) + { + BaseAddress = existingBaseAddress + }; + + // Act + _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create()); + + // Assert + Assert.Equal(existingBaseAddress, httpClient.BaseAddress); + } + + [Fact] + public void Constructor_WhenHttpClientHasNoUserAgent_ShouldAddTheConfiguredUserAgent() + { + // Arrange + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + OpenLibrarySettingsDto settings = _settingsFixture.Create(userAgent: "CustomAgent/2.0"); + + // Act + _ = new OpenLibraryHttpClient(httpClient, settings); + + // Assert + Assert.Equal("CustomAgent/2.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); + } + + [Fact] + public void Constructor_WhenHttpClientAlreadyHasUserAgent_ShouldKeepTheExistingUserAgent() + { + // Arrange + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ExistingAgent/1.0"); + + // Act + _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(userAgent: "ConfiguredAgent/2.0")); + + // Assert + Assert.Equal("ExistingAgent/1.0", httpClient.DefaultRequestHeaders.UserAgent.ToString()); + } + + [Fact] + public void Constructor_WhenContactEmailIsConfigured_ShouldSetTheFromHeader() + { + // Arrange + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + + // Act + _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: "contact@example.com")); + + // Assert + Assert.Equal("contact@example.com", httpClient.DefaultRequestHeaders.From); + } + + [Fact] + public void Constructor_WhenContactEmailIsNotConfigured_ShouldNotSetTheFromHeader() + { + // Arrange + HttpClient httpClient = new(new StubOpenLibraryHttpMessageHandler()); + + // Act + _ = new OpenLibraryHttpClient(httpClient, _settingsFixture.Create(contactEmail: null)); + + // Assert + Assert.Null(httpClient.DefaultRequestHeaders.From); + } + + [Fact] + public async Task GetEditionByIsbnAsync_WhenEditionExists_ShouldRequestTheNormalizedIsbnEndpointAndDeserialize() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/isbn/9780306406157.json", """{"key":"/books/OL1M","title":"Edition Title"}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryEditionResponse? result = await sut.GetEditionByIsbnAsync("978-0-306-40615-7", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Edition Title", result!.Title); + Assert.Equal("/isbn/9780306406157.json", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetEditionByIsbnAsync_WhenEditionIsNotFound_ShouldReturnNull() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryEditionResponse? result = await sut.GetEditionByIsbnAsync("978-0-306-40615-7", CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Single(handler.Requests); + } + + [Fact] + public async Task GetEditionAsync_WhenCalled_ShouldRequestTheBooksEndpointWithTheNormalizedOlid() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL123M.json", """{"key":"/books/OL123M","title":"Edition"}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryEditionResponse? result = await sut.GetEditionAsync("/books/ol123m", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("/books/OL123M.json", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal("/books/OL123M", result!.Key); + } + + [Fact] + public async Task GetEditionAsync_WhenOlidIsNotAnEditionId_ShouldThrowArgumentException() + { + // Arrange + OpenLibraryHttpClient sut = CreateSut(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetEditionAsync("OL123W", CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetWorkAsync_WhenCalled_ShouldRequestTheWorksEndpointWithTheNormalizedOlid() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W.json", """{"key":"/works/OL123W","title":"Work"}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("/works/OL123W.json", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal("Work", result!.Title); + } + + [Fact] + public async Task GetAuthorAsync_WhenCalled_ShouldRequestTheAuthorsEndpointWithTheNormalizedOlid() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/authors/OL1A.json", """{"key":"/authors/OL1A","name":"Test Author"}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryAuthorResponse? result = await sut.GetAuthorAsync("OL1A", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("/authors/OL1A.json", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal("Test Author", result!.Name); + } + + [Fact] + public async Task GetRatingsAsync_WhenCalled_ShouldRequestTheRatingsEndpoint() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W/ratings.json", """{"summary":{"average":4.2,"count":100}}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryRatingsResponse? result = await sut.GetRatingsAsync("OL123W", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("/works/OL123W/ratings.json", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Equal(4.2m, result!.Summary!.Average); + Assert.Equal(100, result.Summary.Count); + } + + [Fact] + public async Task GetRatingsAsync_WhenNumbersAreSerializedAsStrings_ShouldStillDeserializeThem() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W/ratings.json", """{"summary":{"average":"4.2","count":"100"}}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + OpenLibraryRatingsResponse? result = await sut.GetRatingsAsync("OL123W", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(4.2m, result!.Summary!.Average); + Assert.Equal(100, result.Summary.Count); + } + + [Fact] + public async Task GetEditionsAsync_WhenCalled_ShouldRequestTheEditionsEndpointWithTheConfiguredLimit() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W/editions.json", """{"entries":[{"key":"/books/OL1M","title":"Edition"}]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + IReadOnlyList result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None); + + // Assert + OpenLibraryEditionResponse edition = Assert.Single(result); + Assert.Equal("Edition", edition.Title); + Assert.Equal("/works/OL123W/editions.json", handler.Requests[0].RequestUri!.AbsolutePath); + Assert.Contains("limit=50", handler.Requests[0].RequestUri!.Query); + } + + [Theory] + [InlineData(0, "limit=1")] + [InlineData(1, "limit=1")] + [InlineData(1000, "limit=1000")] + [InlineData(5000, "limit=1000")] + public async Task GetEditionsAsync_WhenLimitIsOutsideTheAllowedRange_ShouldClampTheLimit(int limit, string expectedQuery) + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W/editions.json", """{"entries":[]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + await sut.GetEditionsAsync("OL123W", limit, CancellationToken.None); + + // Assert + Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetEditionsAsync_WhenResponseHasNoEntries_ShouldReturnAnEmptyList() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL123W/editions.json", """{"entries":[]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + IReadOnlyList result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetEditionsAsync_WhenEndpointReturnsNotFound_ShouldReturnAnEmptyList() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + OpenLibraryHttpClient sut = CreateSut(handler); + + // Act + IReadOnlyList result = await sut.GetEditionsAsync("OL123W", 50, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task SearchAsync_WhenLookupContainsAllCriteria_ShouldBuildTheQueryWithAllParameters() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: "978-0-306-40615-7", + title: "The Title", + author: "The Author", + languageCode: "en"); + + // Act + IReadOnlyList result = await sut.SearchAsync(lookup, 5, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal("/search.json", handler.Requests[0].RequestUri!.AbsolutePath); + string query = handler.Requests[0].RequestUri!.Query; + Assert.Contains("isbn=9780306406157", query); + Assert.Contains("title=The%20Title", query); + Assert.Contains("author=The%20Author", query); + Assert.Contains("language=en", query); + Assert.Contains("fields=", query); + Assert.Contains("limit=5", query); + } + + [Fact] + public async Task SearchAsync_WhenLookupOnlyHasATitle_ShouldBuildATitleOnlyQuery() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune"); + + // Act + await sut.SearchAsync(lookup, 5, CancellationToken.None); + + // Assert + string query = handler.Requests[0].RequestUri!.Query; + Assert.Contains("title=Dune", query); + Assert.DoesNotContain("isbn=", query); + Assert.DoesNotContain("author=", query); + Assert.DoesNotContain("language=", query); + } + + [Theory] + [InlineData(0, "limit=1")] + [InlineData(100, "limit=100")] + [InlineData(1000, "limit=100")] + public async Task SearchAsync_WhenLimitIsOutsideTheAllowedRange_ShouldClampTheLimit(int limit, string expectedQuery) + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune"); + + // Act + await sut.SearchAsync(lookup, limit, CancellationToken.None); + + // Assert + Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task SearchAsync_WhenResponseContainsDocuments_ShouldReturnTheDocuments() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[{"key":"/works/OL1W","title":"Doc Title"}]}"""); + OpenLibraryHttpClient sut = CreateSut(handler); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune"); + + // Act + IReadOnlyList result = await sut.SearchAsync(lookup, 5, CancellationToken.None); + + // Assert + OpenLibrarySearchDocumentResponse document = Assert.Single(result); + Assert.Equal("Doc Title", document.Title); + } + + [Fact] + public async Task SearchAsync_WhenEndpointReturnsNotFound_ShouldReturnAnEmptyList() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + OpenLibraryHttpClient sut = CreateSut(handler); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Dune"); + + // Act + IReadOnlyList result = await sut.SearchAsync(lookup, 5, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetWorkAsync_WhenFirstAttemptFailsWithServerError_ShouldRetryAndSucceed() + { + // Arrange + int attempts = 0; + StubOpenLibraryHttpMessageHandler handler = new(); + handler.AddRoute( + request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", + _ => attempts++ == 0 + ? new HttpResponseMessage(HttpStatusCode.InternalServerError) + : StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}""")); + OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + + // Act + OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Work", result!.Title); + Assert.Equal(2, handler.Requests.Count); + } + + [Fact] + public async Task GetWorkAsync_WhenFirstAttemptFailsWithTooManyRequests_ShouldRetryAfterTheRetryAfterDelayAndSucceed() + { + // Arrange + int attempts = 0; + StubOpenLibraryHttpMessageHandler handler = new(); + handler.AddRoute( + request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", + _ => + { + if (attempts++ == 0) + { + HttpResponseMessage tooManyRequests = new(HttpStatusCode.TooManyRequests); + tooManyRequests.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(1)); + return tooManyRequests; + } + + return StubOpenLibraryHttpMessageHandler.CreateJsonResponse(HttpStatusCode.OK, """{"key":"/works/OL123W","title":"Work"}"""); + }); + OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + + // Act + OpenLibraryWorkResponse? result = await sut.GetWorkAsync("OL123W", CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Work", result!.Title); + Assert.Equal(2, handler.Requests.Count); + } + + [Fact] + public async Task GetWorkAsync_WhenEveryAttemptFailsWithServerError_ShouldThrowHttpRequestException() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.AddRoute( + request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", + _ => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + + // Act + async Task Act() + { + await sut.GetWorkAsync("OL123W", CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(3, handler.Requests.Count); + } + + [Fact] + public async Task GetWorkAsync_WhenEndpointReturnsBadRequest_ShouldThrowImmediately() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.AddRoute( + request => request.RequestUri!.AbsolutePath == "/works/OL123W.json", + _ => new HttpResponseMessage(HttpStatusCode.BadRequest)); + OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + + // Act + async Task Act() + { + await sut.GetWorkAsync("OL123W", CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Single(handler.Requests); + } + + [Fact] + public async Task GetWorkAsync_WhenRequestsAreCloserThanTheMinimumInterval_ShouldDelayTheSecondRequest() + { + // Arrange + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL1W.json", """{"key":"/works/OL1W","title":"Work"}"""); + OpenLibraryHttpClient sut = CreateSut(handler, _settingsFixture.Create(minimumRequestInterval: TimeSpan.FromMilliseconds(300))); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await sut.GetWorkAsync("OL1W", CancellationToken.None); + await sut.GetWorkAsync("OL1W", CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.ElapsedMilliseconds >= 200, $"Expected the two requests to take at least 200ms, but they took {stopwatch.ElapsedMilliseconds}ms."); + } + + [Fact] + public async Task GetWorkAsync_WhenCancellationIsRequested_ShouldCancelTheOperation() + { + // Arrange + OpenLibraryHttpClient sut = CreateSut(new StubOpenLibraryHttpMessageHandler()); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + async Task Act() + { + await sut.GetWorkAsync("OL123W", cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + private OpenLibraryHttpClient CreateSut(StubOpenLibraryHttpMessageHandler handler, OpenLibrarySettingsDto? settings = null) + { + HttpClient httpClient = new(handler); + return new OpenLibraryHttpClient(httpClient, settings ?? _settingsFixture.Create(minimumRequestInterval: TimeSpan.Zero)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs new file mode 100644 index 00000000..1a98265b --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Mapping/OpenLibraryMapperTests.cs @@ -0,0 +1,431 @@ +#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.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.OpenLibrary.Common.Models.Contracts.Responses; +using Lumina.Plugins.OpenLibrary.Core.Mapping; +using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibraryMapperTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly OpenLibraryEditionResponseFixture _editionResponseFixture = new(); + private readonly OpenLibraryWorkResponseFixture _workResponseFixture = new(); + private readonly OpenLibrarySearchDocumentResponseFixture _searchDocumentResponseFixture = new(); + private readonly OpenLibraryAuthorResponseFixture _authorResponseFixture = new(); + private readonly OpenLibraryRatingsResponseFixture _ratingsResponseFixture = new(); + private readonly OpenLibraryRatingSummaryResponseFixture _ratingSummaryResponseFixture = new(); + private readonly OpenLibraryKeyReferenceResponseFixture _keyReferenceResponseFixture = new(); + private readonly OpenLibraryWorkAuthorResponseFixture _workAuthorResponseFixture = new(); + + [Theory] + [InlineData("978-0-306-40615-7", "9780306406157")] + [InlineData("0-306-40615-2", "0306406152")] + [InlineData("978 0 306 40615 7", "9780306406157")] + [InlineData("9780306406157", "9780306406157")] + [InlineData("0-306-40615-X", "030640615X")] + [InlineData("0-306-40615-x", "030640615X")] + public void NormalizeIsbn_WhenIsbnIsValid_ShouldReturnTheCanonicalForm(string isbn, string expected) + { + // Act + string result = OpenLibraryMapper.NormalizeIsbn(isbn); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("123")] + [InlineData("12345678901")] + [InlineData("1234567890123456")] + [InlineData("ABCDEFGHIJ")] + [InlineData("978030640615A")] + public void NormalizeIsbn_WhenIsbnIsInvalid_ShouldThrowArgumentException(string isbn) + { + // Act + Action act = () => OpenLibraryMapper.NormalizeIsbn(isbn); + + // Assert + Assert.Throws(act); + } + + [Theory] + [InlineData("/works/OL12345W", "W", "OL12345W")] + [InlineData("/books/OL1M", "M", "OL1M")] + [InlineData("OL999W", "W", "OL999W")] + [InlineData("https://openlibrary.org/works/OL2W", "W", "OL2W")] + [InlineData("/works/ol3w", "W", "OL3W")] + [InlineData("/works/OL123W/", "W", "OL123W")] + public void ExtractOlid_WhenKeyContainsAMatchingOlid_ShouldReturnTheCanonicalOlid(string key, string expectedSuffix, string expected) + { + // Act + string? result = OpenLibraryMapper.ExtractOlid(key, expectedSuffix[0]); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(null, "W")] + [InlineData("", "W")] + [InlineData(" ", "W")] + [InlineData("/works/OL1A", "W")] + [InlineData("/works/not-an-olid", "W")] + [InlineData("OL1", "W")] + [InlineData("/books/OL1M", "W")] + public void ExtractOlid_WhenKeyDoesNotContainAMatchingOlid_ShouldReturnNull(string? key, string expectedSuffix) + { + // Act + string? result = OpenLibraryMapper.ExtractOlid(key, expectedSuffix[0]); + + // Assert + Assert.Null(result); + } + + [Theory] + [InlineData("Mass Market Paperback", BookFormat.MassMarketPaperback)] + [InlineData("mass market paperback", BookFormat.MassMarketPaperback)] + [InlineData("Trade Paperback", BookFormat.TradePaperback)] + [InlineData("Paperback", BookFormat.Paperback)] + [InlineData("Softcover", BookFormat.Paperback)] + [InlineData("Hardcover", BookFormat.Hardcover)] + [InlineData("Hard cover", BookFormat.Hardcover)] + [InlineData("Hardback", BookFormat.Hardcover)] + [InlineData("Clothbound", BookFormat.Hardcover)] + [InlineData("eBook", BookFormat.eBook)] + [InlineData("E-book", BookFormat.eBook)] + [InlineData("Electronic", BookFormat.eBook)] + [InlineData("Audiobook", BookFormat.Audiobook)] + [InlineData("Audio Book", BookFormat.Audiobook)] + [InlineData("Audio CD", BookFormat.Audiobook)] + [InlineData("Large Print", BookFormat.LargePrint)] + [InlineData("Board Book", BookFormat.BoardBook)] + [InlineData("Spiral", BookFormat.SpiralBound)] + [InlineData("Library Binding", BookFormat.LibraryBinding)] + [InlineData("Leather", BookFormat.LeatherBound)] + [InlineData("Pop-up", BookFormat.PopupBook)] + [InlineData("Popup", BookFormat.PopupBook)] + public void MapFormat_WhenPhysicalFormatIsRecognized_ShouldReturnTheMappedBookFormat(string physicalFormat, BookFormat expected) + { + // Act + BookFormat? result = OpenLibraryMapper.MapFormat(physicalFormat); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("3D Printed")] + [InlineData("Unknown Format")] + public void MapFormat_WhenPhysicalFormatIsNotRecognized_ShouldReturnNull(string? physicalFormat) + { + // Act + BookFormat? result = OpenLibraryMapper.MapFormat(physicalFormat); + + // Assert + Assert.Null(result); + } + + [Fact] + public void MapSearchCandidate_WhenCalledWithASearchDocument_ShouldMapTheDocumentFields() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibrarySearchDocumentResponse document = _searchDocumentResponseFixture.Create( + key: "/works/OL12345W", + title: "Search Title", + authorNames: ["Search Author"], + firstPublishYear: 2003, + publishers: ["Search Publisher"], + publishPlaces: ["London"], + subjects: ["Science fiction", "Space"], + isbns: ["978-0-306-40615-7"], + numberOfPagesMedian: 250, + ratingsAverage: 4.1m, + ratingsCount: 42, + lccn: ["79042755"], + oclc: ["123456789"]); + + // Act + AddBookRequest result = OpenLibraryMapper.MapSearchCandidate(lookup, document); + + // Assert + Assert.Equal(lookup.LibraryId, result.LibraryId); + Assert.Equal(lookup.Path, result.Path); + Assert.Equal("Search Title", result.Metadata!.Title); + Assert.Equal(2003, result.Metadata.ReleaseInfo!.OriginalReleaseYear); + Assert.Equal("Search Publisher", result.Metadata.Publisher); + Assert.Equal(250, result.Metadata.PageCount); + Assert.Contains(result.Metadata.Genres!, genre => genre.Name == "Science fiction"); + Assert.DoesNotContain(result.Metadata.Genres!, genre => genre.Name == "Space"); + Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Science fiction"); + Assert.Contains(result.Metadata.Tags!, tag => tag.Name == "Space"); + Assert.Equal("London", result.Metadata.ReleaseInfo.ReleaseCountry); + BookRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(4.1m, rating.Value); + Assert.Equal(5m, rating.MaxValue); + Assert.Equal(BookRatingSource.OpenLibrary, rating.Source); + Assert.Equal(42, rating.VoteCount); + Assert.Equal("79042755", result.LCCN); + Assert.Equal("123456789", result.OCLCNumber); + Assert.Equal("OL12345W", result.OpenLibraryId); + Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Search Author" && contributor.Role!.Name == "Author"); + } + + [Fact] + public void MapDetailed_WhenEditionAndWorkAreProvided_ShouldMapAllBookRequestFields() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7"); + JsonElement identifiers = JsonDocument.Parse("""{"amazon":["B000001"],"goodreads":["12345"],"google":["gid"],"librarything":["ltid"],"barnesandnoble":["bnid"],"apple":["apid"]}""").RootElement; + OpenLibraryEditionResponse edition = _editionResponseFixture.Create( + key: "/books/OL100M", + title: "Edition Title", + publishDate: "2010-05-01", + publishers: ["Publisher Co"], + publishPlaces: ["New York"], + numberOfPages: 320, + physicalFormat: "Hardcover", + editionName: "First Edition", + series: ["The Series"], + volume: "Vol. 3", + isbn10: ["0306406152"], + isbn13: ["9780306406157"], + lccn: ["79042755"], + oclcNumbers: ["1234567"], + identifiers: identifiers, + languages: [_keyReferenceResponseFixture.Create(key: "/languages/eng")], + works: [_keyReferenceResponseFixture.Create(key: "/works/OL200W")], + contributions: ["John Smith (Illustrator)"]); + OpenLibraryWorkResponse work = _workResponseFixture.Create( + key: "/works/OL200W", + title: "Work Title", + originalTitle: "Original Title", + description: JsonDocument.Parse("""{"value":"A work description"}""").RootElement, + firstPublishDate: "1987-06-01", + subjects: ["Science fiction", "History", "Space"], + genres: ["Fantasy"], + authors: [_workAuthorResponseFixture.Create(author: _keyReferenceResponseFixture.Create(key: "/authors/OL1A"))], + originalLanguages: [_keyReferenceResponseFixture.Create(key: "/languages/fre")]); + OpenLibraryAuthorResponse author = _authorResponseFixture.Create(key: "/authors/OL1A", name: "Test Author", personalName: "Test Personal Name"); + OpenLibraryRatingsResponse ratings = _ratingsResponseFixture.Create(_ratingSummaryResponseFixture.Create(average: 4.2m, count: 100)); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, work, [author], ratings); + + // Assert + Assert.Equal(lookup.LibraryId, result.LibraryId); + Assert.Equal(lookup.Path, result.Path); + Assert.Equal("Edition Title", result.Metadata!.Title); + Assert.Equal("Original Title", result.Metadata.OriginalTitle); + Assert.Equal("A work description", result.Metadata.Description); + Assert.Equal(new DateOnly(1987, 6, 1), result.Metadata.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1987, result.Metadata.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(2010, 5, 1), result.Metadata.ReleaseInfo.ReReleaseDate); + Assert.Equal(2010, result.Metadata.ReleaseInfo.ReReleaseYear); + Assert.Equal("New York", result.Metadata.ReleaseInfo.ReleaseCountry); + Assert.Equal("First Edition", result.Metadata.ReleaseInfo.ReleaseVersion); + GenreDto genre = Assert.Single(result.Metadata.Genres!); + Assert.Equal("Fantasy", genre.Name); + Assert.Equal(3, result.Metadata.Tags!.Count); + Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Science fiction"); + Assert.Contains(result.Metadata.Tags, tag => tag.Name == "History"); + Assert.Contains(result.Metadata.Tags, tag => tag.Name == "Space"); + Assert.Equal("en", result.Metadata.Language!.LanguageCode); + Assert.False(string.IsNullOrWhiteSpace(result.Metadata.Language.LanguageName)); + Assert.Equal("fre", result.Metadata.OriginalLanguage!.LanguageCode); + Assert.Equal("fre", result.Metadata.OriginalLanguage.LanguageName); + Assert.Null(result.Metadata.OriginalLanguage.NativeName); + Assert.Equal("Publisher Co", result.Metadata.Publisher); + Assert.Equal(320, result.Metadata.PageCount); + Assert.Equal(BookFormat.Hardcover, result.Format); + Assert.Equal("First Edition", result.Edition); + Assert.Equal(3, result.VolumeNumber); + Assert.Equal("The Series", result.Series!.Title); + Assert.Equal("B000001", result.ASIN); + Assert.Equal("12345", result.GoodreadsId); + Assert.Equal("79042755", result.LCCN); + Assert.Equal("1234567", result.OCLCNumber); + Assert.Equal("OL100M", result.OpenLibraryId); + Assert.Equal("ltid", result.LibraryThingId); + Assert.Equal("gid", result.GoogleBooksId); + Assert.Equal("bnid", result.BarnesAndNobleId); + Assert.Equal("apid", result.AppleBooksId); + Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.ISBNs!, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author" && contributor.Name.LegalName == "Test Personal Name" && contributor.Role!.Name == "Author"); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "John Smith" && contributor.Role!.Name == "Illustrator" && contributor.Role.Category == "Art"); + BookRatingDto mappedRating = Assert.Single(result.Ratings!); + Assert.Equal(4.2m, mappedRating.Value); + Assert.Equal(5m, mappedRating.MaxValue); + Assert.Equal(BookRatingSource.OpenLibrary, mappedRating.Source); + Assert.Equal(100, mappedRating.VoteCount); + } + + [Fact] + public void MapDetailed_WhenWorkHasNoExplicitGenres_ShouldDeriveGenresFromTheGenreLikeSubjects() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibraryWorkResponse work = _workResponseFixture.Create(subjects: ["Science fiction", "History", "Space"]); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); + + // Assert + Assert.Equal(2, result.Metadata!.Genres!.Count); + Assert.Contains(result.Metadata.Genres, genre => genre.Name == "Science fiction"); + Assert.Contains(result.Metadata.Genres, genre => genre.Name == "History"); + Assert.DoesNotContain(result.Metadata.Genres, genre => genre.Name == "Space"); + } + + [Fact] + public void MapDetailed_WhenWorkHasNoFirstPublishDate_ShouldUseTheFallbackFirstPublishYear() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(firstPublishYear: 2001); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); + + // Assert + Assert.Equal(2001, result.Metadata!.ReleaseInfo!.OriginalReleaseYear); + Assert.Null(result.Metadata.ReleaseInfo.OriginalReleaseDate); + } + + [Fact] + public void MapDetailed_WhenLanguageKeyIsUnknown_ShouldUseTheRawCodeAsTheLanguage() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibraryEditionResponse edition = _editionResponseFixture.Create(languages: [_keyReferenceResponseFixture.Create(key: "/languages/xxq")]); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); + + // Assert + Assert.NotNull(result.Metadata!.Language); + Assert.Equal("xxq", result.Metadata.Language!.LanguageCode); + Assert.Equal("xxq", result.Metadata.Language.LanguageName); + Assert.Null(result.Metadata.Language.NativeName); + } + + [Fact] + public void MapDetailed_WhenDescriptionIsAPlainString_ShouldReadItDirectly() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibraryWorkResponse work = _workResponseFixture.Create(description: JsonDocument.Parse("\"A plain description\"").RootElement); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, work, [], null); + + // Assert + Assert.Equal("A plain description", result.Metadata!.Description); + } + + [Fact] + public void MapDetailed_WhenNoExternalDataIsAvailable_ShouldMapTheLookupItselfAndLeaveTheRestNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(isbn: "978-0-306-40615-7"); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, null); + + // Assert + Assert.Equal(lookup.LibraryId, result.LibraryId); + Assert.Equal(lookup.Path, result.Path); + Assert.NotNull(result.Metadata); + Assert.Null(result.Metadata!.Title); + Assert.Null(result.Format); + Assert.Null(result.Edition); + Assert.Null(result.OpenLibraryId); + Assert.Contains(result.ISBNs!, isbn => isbn.Value == "9780306406157"); + Assert.Empty(result.Ratings!); + Assert.Empty(result.Contributors!); + } + + [Fact] + public void MapDetailed_WhenRatingsAreOnlyAvailableInTheFallbackDocument_ShouldUseTheFallbackRatings() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create(ratingsAverage: 3.5m, ratingsCount: 10); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, null, null, [], null, fallback); + + // Assert + BookRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(3.5m, rating.Value); + Assert.Equal(10, rating.VoteCount); + } + + [Fact] + public void MapDetailed_WhenVolumeIsContainedInTheEditionSeries_ShouldParseTheVolumeNumber() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibraryEditionResponse edition = _editionResponseFixture.Create(series: ["Book 2 of the trilogy"]); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null); + + // Assert + Assert.Equal(2, result.VolumeNumber); + Assert.Equal("Book 2 of the trilogy", result.Series!.Title); + } + + [Fact] + public void MapDetailed_WhenExternalIdsComeFromSourceRecordsAndFallback_ShouldMapThem() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + OpenLibraryEditionResponse edition = _editionResponseFixture.Create( + sourceRecords: ["amazon:B000002", "google:gid2"], + oclcNumbers: ["999999"], + isbn13: ["9780306406157"]); + OpenLibrarySearchDocumentResponse fallback = _searchDocumentResponseFixture.Create( + amazonIds: ["B000003"], + goodreadsIds: ["777"], + googleIds: ["gid3"], + libraryThingIds: ["lt3"], + lccn: ["79042756"], + oclc: ["888888"]); + + // Act + AddBookRequest result = OpenLibraryMapper.MapDetailed(lookup, edition, null, [], null, fallback); + + // Assert + Assert.Equal("B000002", result.ASIN); + Assert.Equal("777", result.GoodreadsId); + Assert.Equal("gid2", result.GoogleBooksId); + Assert.Equal("lt3", result.LibraryThingId); + Assert.Equal("79042756", result.LCCN); + Assert.Equal("999999", result.OCLCNumber); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs new file mode 100644 index 00000000..5b3a6665 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryBookMetadataProviderTests.cs @@ -0,0 +1,448 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +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.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; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibraryBookMetadataProviderTests +{ + private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + 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] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("Open Library", result); + } + + [Fact] + public void SupportedLibraryType_WhenCalled_ShouldReturnBook() + { + // Arrange + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + LibraryType result = sut.SupportedLibraryType; + + // Assert + Assert.Equal(LibraryType.Book, result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasAnIsbn_ShouldResolveTheExactEditionWithoutSearching() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: "978-0-306-40615-7", + openLibraryId: null, + title: null, + author: null, + languageCode: null); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/isbn/9780306406157.json", EDITION_JSON); + handler.MapPath("/works/OL200W.json", WORK_JSON); + handler.MapPath("/authors/OL1A.json", AUTHOR_JSON); + handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Edition Title", metadata.Title); + Assert.Equal("Publisher Co", metadata.Publisher); + Assert.Equal(320, metadata.PageCount); + Assert.Equal(BookFormat.Hardcover, metadata.Format); + Assert.Equal("First Edition", metadata.Edition); + Assert.Equal(3, metadata.VolumeNumber); + Assert.Equal("The Series", metadata.Series!.Title); + Assert.Equal("OL100M", metadata.OpenLibraryId); + Assert.Contains(metadata.Isbns!, isbn => isbn.Value == "9780306406157"); + Assert.DoesNotContain(handler.Requests, request => request.RequestUri!.AbsolutePath == "/search.json"); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasAnIsbnButNoMatchExists_ShouldReturnAnEmptyList() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: "978-0-306-40615-7", + openLibraryId: null, + title: null, + author: null, + languageCode: null); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasAWorkOpenLibraryId_ShouldResolveTheWorkAndItsBestEdition() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: null, + openLibraryId: "OL200W", + title: null, + author: null, + languageCode: null); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL200W.json", WORK_JSON); + handler.MapPath("/works/OL200W/editions.json", EDITIONS_JSON); + handler.MapPath("/authors/OL1A.json", AUTHOR_JSON); + handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Edition Title", metadata.Title); + Assert.Equal("OL100M", metadata.OpenLibraryId); + Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/works/OL200W/editions.json"); + Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/works/OL200W/ratings.json"); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasOnlyATitle_ShouldSearchAndMapTheSearchCandidates() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title"); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[{"key":"/works/OL1W","title":"Search Title","author_name":["Search Author"],"first_publish_year":2001,"publisher":["Search Publisher"],"subject":["Science fiction"],"isbn":["9780306406157"],"number_of_pages_median":250},{"key":"/works/OL999W"}]}"""); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Search Title", metadata.Title); + Assert.Equal(2001, metadata.ReleaseInfo!.OriginalReleaseYear); + Assert.Equal("Search Publisher", metadata.Publisher); + Assert.Equal(250, metadata.PageCount); + Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/search.json"); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenSearchReturnsNoResults_ShouldReturnAnEmptyList() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title"); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[]}"""); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupIsNull_ShouldThrowArgumentNullException() + { + // Arrange + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetSearchResultsAsync(null!, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasAnEmptyLibraryId_ShouldThrowArgumentException() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(libraryId: Guid.Empty); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasNoPath_ShouldThrowArgumentNullException() + { + // Arrange + BookMetadataLookupDto lookup = new(Guid.NewGuid(), null!, Isbn: "978-0-306-40615-7"); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupPathIsWhiteSpace_ShouldThrowArgumentException() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " ", isbn: "978-0-306-40615-7"); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenLookupHasNoSearchCriteria_ShouldThrowArgumentException() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", isbn: null, openLibraryId: null, title: null, author: null, languageCode: null); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetMetadataAsync_WhenAnExactMatchExists_ShouldReturnTheMappedMetadata() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: "978-0-306-40615-7", + openLibraryId: null, + title: null, + author: null, + languageCode: null); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/isbn/9780306406157.json", EDITION_JSON); + handler.MapPath("/works/OL200W.json", WORK_JSON); + handler.MapPath("/authors/OL1A.json", AUTHOR_JSON); + handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + BookMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Edition Title", result!.Title); + } + + [Fact] + public async Task GetMetadataAsync_WhenNoMatchExists_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: "978-0-306-40615-7", + openLibraryId: null, + title: null, + author: null, + languageCode: null); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + BookMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetBookAsync_WhenLookupHasAnEditionOpenLibraryId_ShouldResolveTheEditionWorkAuthorsAndRatings() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: null, + openLibraryId: "OL100M", + title: null, + author: null, + languageCode: null); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/books/OL100M.json", EDITION_JSON); + handler.MapPath("/works/OL200W.json", WORK_JSON); + handler.MapPath("/authors/OL1A.json", AUTHOR_JSON); + handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + AddBookRequest? result = await sut.GetBookAsync(lookup); + + // Assert + Assert.NotNull(result); + Assert.Equal("Edition Title", result!.Metadata!.Title); + Assert.Equal("A work description", result.Metadata.Description); + Assert.Equal("OL100M", result.OpenLibraryId); + Assert.Equal(BookFormat.Hardcover, result.Format); + Assert.Equal(3, result.VolumeNumber); + Assert.Contains(result.Contributors!, contributor => contributor.Name!.DisplayName == "Test Author"); + Assert.Contains(result.Ratings!, rating => rating.Value == 4.2m); + } + + [Fact] + public async Task GetBookAsync_WhenLookupHasAWorkOpenLibraryIdAndNoMatchingEditions_ShouldReturnABookFromTheWorkDataOnly() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: null, + openLibraryId: "OL200W", + title: null, + author: null, + languageCode: null); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/works/OL200W.json", WORK_JSON); + handler.MapPath("/works/OL200W/editions.json", """{"entries":[]}"""); + handler.MapPath("/authors/OL1A.json", AUTHOR_JSON); + handler.MapPath("/works/OL200W/ratings.json", RATINGS_JSON); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + AddBookRequest? result = await sut.GetBookAsync(lookup); + + // Assert + Assert.NotNull(result); + Assert.Equal("Work Title", result!.Metadata!.Title); + Assert.Equal("OL200W", result.OpenLibraryId); + } + + [Fact] + public async Task GetBookAsync_WhenSearchResultHasOnlyAnEditionKey_ShouldResolveTheEditionByItsFirstEditionKey() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title"); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[{"key":"/books/OL500M","edition_key":["OL600M"]}]}"""); + handler.MapPath("/books/OL600M.json", """{"key":"/books/OL600M","title":"Fallback Edition"}"""); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + AddBookRequest? result = await sut.GetBookAsync(lookup); + + // Assert + Assert.NotNull(result); + Assert.Equal("Fallback Edition", result!.Metadata!.Title); + Assert.Equal("OL600M", result.OpenLibraryId); + Assert.Contains(handler.Requests, request => request.RequestUri!.AbsolutePath == "/books/OL600M.json"); + } + + [Fact] + public async Task GetBookAsync_WhenSearchReturnsNoResults_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: "/books/title.epub", title: "Search Title"); + StubOpenLibraryHttpMessageHandler handler = new(); + handler.MapPath("/search.json", """{"docs":[]}"""); + OpenLibraryBookMetadataProvider sut = CreateProvider(handler); + + // Act + AddBookRequest? result = await sut.GetBookAsync(lookup); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetBookAsync_WhenOpenLibraryIdHasAnUnknownSuffix_ShouldThrowArgumentException() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create( + isbn: null, + openLibraryId: "OL123X", + title: null, + author: null, + languageCode: null); + OpenLibraryBookMetadataProvider sut = CreateProvider(new StubOpenLibraryHttpMessageHandler()); + + // Act + async Task Act() + { + await sut.GetBookAsync(lookup); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + 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); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs new file mode 100644 index 00000000..a3df9bde --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/OpenLibraryPluginTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +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; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibraryPluginTests +{ + private readonly OpenLibraryPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(OpenLibraryPlugin.s_pluginId, result); + Assert.Equal(new Guid("08b17802-7f9c-4c4b-9d7f-b507bbed3e58"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Open Library 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("Retrieves book and edition metadata from Open Library.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnAllDeclaredSettingsWithTheirDefaults() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Equal(4, result.Count); + + PluginSettingDescriptorDto contactEmail = result[0]; + Assert.Equal(OpenLibrarySettingsKeys.CONTACT_EMAIL, contactEmail.Key); + Assert.Equal("Contact Email", contactEmail.Label); + Assert.Equal(PluginSettingType.Text, contactEmail.Type); + Assert.Null(contactEmail.DefaultValue); + + PluginSettingDescriptorDto searchResultLimit = result[1]; + Assert.Equal(OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT, searchResultLimit.Key); + Assert.Equal("Search Result Limit", searchResultLimit.Label); + Assert.Equal(PluginSettingType.Number, searchResultLimit.Type); + Assert.Equal("10", searchResultLimit.DefaultValue); + + PluginSettingDescriptorDto workEditionLimit = result[2]; + Assert.Equal(OpenLibrarySettingsKeys.WORK_EDITION_LIMIT, workEditionLimit.Key); + Assert.Equal("Work Edition Limit", workEditionLimit.Label); + Assert.Equal(PluginSettingType.Number, workEditionLimit.Type); + Assert.Equal("50", workEditionLimit.DefaultValue); + + PluginSettingDescriptorDto minimumRequestInterval = result[3]; + Assert.Equal(OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, minimumRequestInterval.Key); + Assert.Equal("Minimum Request Interval (seconds)", minimumRequestInterval.Label); + Assert.Equal(PluginSettingType.Number, minimumRequestInterval.Type); + Assert.Equal("1.1", minimumRequestInterval.DefaultValue); + } + + [Fact] + public void GetSettingsSchema_WhenCalledRepeatedly_ShouldReturnAnIndependentSchemaEachTime() + { + // Act + IReadOnlyList first = _sut.GetSettingsSchema(); + IReadOnlyList second = _sut.GetSettingsSchema(); + + // Assert + Assert.NotSame(first, second); + Assert.Equal(first.Count, second.Count); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataProviderAndHttpClient() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(OpenLibraryPlugin.s_pluginId)); + Assert.NotNull(serviceProvider.GetService()); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs new file mode 100644 index 00000000..b572683e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Core/Settings/OpenLibrarySettingsLoaderTests.cs @@ -0,0 +1,229 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.OpenLibrary.Common.Models.DTO.Settings; +using Lumina.Plugins.OpenLibrary.Core.Settings; +using Lumina.Plugins.OpenLibrary.Fixtures.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.OpenLibrary.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpenLibrarySettingsLoaderTests +{ + private readonly OpenLibrarySettingsDtoFixture _settingsFixture = new(); + + [Fact] + public void Apply_WhenStoredSettingsContainValidValues_ShouldOverlayThemOntoTheRuntimeSettings() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.CONTACT_EMAIL] = " contact@example.com ", + [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "25", + [OpenLibrarySettingsKeys.WORK_EDITION_LIMIT] = "75", + [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal("contact@example.com", settings.ContactEmail); + Assert.Equal(25, settings.SearchResultLimit); + Assert.Equal(75, settings.WorkEditionLimit); + Assert.Equal(TimeSpan.FromSeconds(2.5), settings.MinimumRequestInterval); + } + + [Fact] + public void Apply_WhenStoredSettingsAreEmpty_ShouldKeepTheRuntimeSettingsDefaults() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create( + userAgent: "Lumina-OpenLibrary/1.0", + searchResultLimit: 10, + workEditionLimit: 50, + minimumRequestInterval: TimeSpan.FromSeconds(1.1)); + Dictionary storedSettings = []; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal("Lumina-OpenLibrary/1.0", settings.UserAgent); + Assert.Null(settings.ContactEmail); + Assert.Equal(10, settings.SearchResultLimit); + Assert.Equal(50, settings.WorkEditionLimit); + Assert.Equal(TimeSpan.FromSeconds(1.1), settings.MinimumRequestInterval); + } + + [Fact] + public void Apply_WhenStoredSettingsContainUnknownKeys_ShouldIgnoreThem() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 10, workEditionLimit: 50); + Dictionary storedSettings = new() + { + ["UnknownSetting"] = "value" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(10, settings.SearchResultLimit); + Assert.Equal(50, settings.WorkEditionLimit); + } + + [Fact] + public void Apply_WhenContactEmailIsWhiteSpace_ShouldSetItToNull() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.CONTACT_EMAIL] = " " + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Null(settings.ContactEmail); + } + + [Fact] + public void Apply_WhenSearchResultLimitIsNotParsable_ShouldKeepTheCurrentValue() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 10); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(10, settings.SearchResultLimit); + } + + [Fact] + public void Apply_WhenSearchResultLimitIsNotParsableAndCurrentValueWasChanged_ShouldKeepTheChangedValue() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(searchResultLimit: 7); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = "not-a-number" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(7, settings.SearchResultLimit); + } + + [Theory] + [InlineData("-5", 1)] + [InlineData("0", 1)] + [InlineData("1", 1)] + [InlineData(" 12 ", 12)] + [InlineData("300", 300)] + public void Apply_WhenSearchResultLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected) + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.SEARCH_RESULT_LIMIT] = storedValue + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(expected, settings.SearchResultLimit); + } + + [Theory] + [InlineData("-5", 1)] + [InlineData("0", 1)] + [InlineData("80", 80)] + public void Apply_WhenWorkEditionLimitIsParsable_ShouldClampItToAtLeastOne(string storedValue, int expected) + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.WORK_EDITION_LIMIT] = storedValue + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(expected, settings.WorkEditionLimit); + } + + [Fact] + public void Apply_WhenMinimumRequestIntervalIsNegative_ShouldClampItToZero() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "-3" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(TimeSpan.Zero, settings.MinimumRequestInterval); + } + + [Theory] + [InlineData("1.5", 1500)] + [InlineData("0.25", 250)] + [InlineData("0", 0)] + public void Apply_WhenMinimumRequestIntervalUsesInvariantCultureDecimalSeparator_ShouldParseIt(string storedValue, int expectedMilliseconds) + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedValue + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(TimeSpan.FromMilliseconds(expectedMilliseconds), settings.MinimumRequestInterval); + } + + [Fact] + public void Apply_WhenMinimumRequestIntervalIsNotParsable_ShouldKeepTheCurrentValue() + { + // Arrange + OpenLibrarySettingsDto settings = _settingsFixture.Create(minimumRequestInterval: TimeSpan.FromSeconds(1.1)); + Dictionary storedSettings = new() + { + [OpenLibrarySettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "fast" + }; + + // Act + OpenLibrarySettingsLoader.Apply(settings, storedSettings); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(1.1), settings.MinimumRequestInterval); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.UnitTests.csproj new file mode 100644 index 00000000..f1fb9e72 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.OpenLibrary.UnitTests/Lumina.Plugins.OpenLibrary.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.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs new file mode 100644 index 00000000..d32b843a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.AddLibrary; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.AddLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddLibraryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddLibraryEndpoint _sut; + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddLibraryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnCreatedResultWithLibraryResponse() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LibraryResponse expectedResponse = _libraryResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Created createdResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, createdResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Conflict("Library.AlreadyExists", "The media library already exists."); + _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.Status409Conflict, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.AlreadyExists", problemDetails.ProblemDetails.Title); + Assert.Equal("The media library already exists.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status409Conflict, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddLibraryCommandToSender() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Title == request.Title && + command.LibraryType == request.LibraryType && + command.ContentLocations == request.ContentLocations && + command.CoverImage == request.CoverImage && + command.IsEnabled == request.IsEnabled && + command.IsLocked == request.IsLocked && + command.DownloadMetadataFromWeb == request.DownloadMetadataFromWeb && + command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && + command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddLibraryRequest request = _addLibraryRequestFixture.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(_libraryResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs new file mode 100644 index 00000000..3d855f74 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibrariesScan/CancelLibrariesScanEndpointTests.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibrariesScan; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.CancelLibrariesScan; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibrariesScanEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly CancelLibrariesScanEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public CancelLibrariesScanEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContent() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("LibraryScan.Cancel.Failed", "Failed to cancel the running library scans."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryScan.Cancel.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to cancel the running library scans.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCancelLibrariesScanCommandToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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(FastEndpoints.EmptyRequest.Instance, 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/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs new file mode 100644 index 00000000..e6250145 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/CancelLibraryScan/CancelLibraryScanEndpointTests.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibraryScan; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.CancelLibraryScan; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.CancelLibraryScan; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CancelLibraryScanEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly CancelLibraryScanEndpoint _sut; + private readonly CancelLibraryScanRequestFixture _cancelLibraryScanRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public CancelLibraryScanEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnNoContent() + { + // Arrange + CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.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 + Assert.IsType(result); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryScan.NotFound", "The requested library scan 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("LibraryScan.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested library scan 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_ShouldSendCancelLibraryScanCommandToSender() + { + // Arrange + CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.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.ScanId == request.ScanId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancelLibraryScanRequest request = _cancelLibraryScanRequestFixture.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/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs new file mode 100644 index 00000000..611d3de9 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/DeleteLibrary/DeleteLibraryEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.DeleteLibrary; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.DeleteLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeleteLibraryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeleteLibraryEndpoint _sut; + private readonly DeleteLibraryRequestFixture _deleteLibraryRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public DeleteLibraryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.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_ShouldSendDeleteLibraryCommandToSender() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Deleted)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == request.Id), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + DeleteLibraryRequest request = _deleteLibraryRequestFixture.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.Deleted); + }, 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/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs new file mode 100644 index 00000000..37ce926d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetEnabledLibraries/GetEnabledLibrariesEndpointTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries; +using Lumina.Contracts.Fixtures.Core.Responses.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.GetEnabledLibraries; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetEnabledLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetEnabledLibrariesEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetEnabledLibrariesEndpoint _sut; + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetEnabledLibrariesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + LibraryResponse[] expectedResponses = [_libraryResponseFixture.Create(), _libraryResponseFixture.Create()]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Library.GetEnabledLibraries.Failed", "Failed to get the enabled media libraries."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.GetEnabledLibraries.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to get the enabled media libraries.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetEnabledLibrariesQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Array.Empty())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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(Array.Empty()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, 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/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs new file mode 100644 index 00000000..d7bd168b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraries/GetLibrariesEndpointTests.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries; +using Lumina.Contracts.Fixtures.Core.Responses.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.GetLibraries; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibrariesEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetLibrariesEndpoint _sut; + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibrariesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + LibraryResponse[] expectedResponses = [_libraryResponseFixture.Create(), _libraryResponseFixture.Create()]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Library.GetLibraries.Failed", "Failed to get the media libraries."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.GetLibraries.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to get the media libraries.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibrariesQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Array.Empty())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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(Array.Empty()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, 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/Library/Management/GetLibrary/GetLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs new file mode 100644 index 00000000..4c4f6823 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibrary/GetLibraryEndpointTests.cs @@ -0,0 +1,132 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibrary; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetLibraryEndpoint _sut; + private readonly GetLibraryRequestFixture _getLibraryRequestFixture = new(); + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryResponse() + { + // Arrange + GetLibraryRequest request = _getLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryRequest request = _getLibraryRequestFixture.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_ShouldSendGetLibraryQueryToSender() + { + // Arrange + GetLibraryRequest request = _getLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.Id == request.Id), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryRequest request = _getLibraryRequestFixture.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(_libraryResponseFixture.Create(id: request.Id)); + }, 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/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs new file mode 100644 index 00000000..d5b39d5c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetLibraryScanProgress/GetLibraryScanProgressEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScanProgress; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.GetLibraryScanProgress; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetLibraryScanProgress; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryScanProgressEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetLibraryScanProgressEndpoint _sut; + private readonly GetLibraryScanProgressRequestFixture _getLibraryScanProgressRequestFixture = new(); + private readonly MediaLibraryScanProgressResponseFixture _mediaLibraryScanProgressResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryScanProgressEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMediaLibraryScanProgressResponse() + { + // Arrange + GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + MediaLibraryScanProgressResponse expectedResponse = _mediaLibraryScanProgressResponseFixture.Create(scanId: request.ScanId, libraryId: request.LibraryId, totalJobs: 5, completedJobs: 2, currentJobProgress: null, status: "Running", overallProgressPercentage: 40M); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryScan.NotFound", "The requested library scan 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("LibraryScan.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested library scan 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_ShouldSendGetLibraryScanProgressQueryToSender() + { + // Arrange + GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_mediaLibraryScanProgressResponseFixture.Create(scanId: request.ScanId, libraryId: request.LibraryId, totalJobs: 5, completedJobs: 2, currentJobProgress: null, status: "Running", overallProgressPercentage: 40M))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == request.LibraryId && + query.ScanId == request.ScanId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryScanProgressRequest request = _getLibraryScanProgressRequestFixture.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(_mediaLibraryScanProgressResponseFixture.Create(scanId: request.ScanId, libraryId: request.LibraryId, totalJobs: 5, completedJobs: 2, currentJobProgress: null, status: "Running", overallProgressPercentage: 40M)); + }, 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/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs new file mode 100644 index 00000000..e3bcca5b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/GetRunningLibraryScans/GetRunningLibraryScansEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans; +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.GetRunningLibraryScans; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.GetRunningLibraryScans; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetRunningLibraryScansEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetRunningLibraryScansEndpoint _sut; + private readonly MediaLibraryScanProgressResponseFixture _mediaLibraryScanProgressResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetRunningLibraryScansEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMediaLibraryScanProgressResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponses = + [ + _mediaLibraryScanProgressResponseFixture.Create(), + _mediaLibraryScanProgressResponseFixture.Create() + ]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("LibraryScan.GetRunning.Failed", "Failed to get the running library scans."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryScan.GetRunning.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to get the running library scans.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetRunningLibraryScansQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Array.Empty().AsEnumerable())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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(Array.Empty().AsEnumerable()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, 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/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs new file mode 100644 index 00000000..4031193b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibraries/ScanLibrariesEndpointTests.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibraries; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.ScanLibraries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibrariesEndpointTests +{ + private readonly ICommandHandler>> _mockHandler; + private readonly ScanLibrariesEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public ScanLibrariesEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMediaLibraryScanResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + IEnumerable expectedResponses = + [ + new MediaLibraryScanResponse(Guid.NewGuid(), Guid.NewGuid()), + new MediaLibraryScanResponse(Guid.NewGuid(), Guid.NewGuid()) + ]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Library.Scan.Failed", "Failed to scan the media libraries."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.Scan.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to scan the media libraries.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendScanLibrariesCommandToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Array.Empty().AsEnumerable())); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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(Array.Empty().AsEnumerable()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, 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/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs new file mode 100644 index 00000000..8e533e4b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/ScanLibrary/ScanLibraryEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.ScanLibrary; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.ScanLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ScanLibraryEndpoint _sut; + private readonly ScanLibraryRequestFixture _scanLibraryRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ScanLibraryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithMediaLibraryScanResponse() + { + // Arrange + ScanLibraryRequest request = _scanLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + MediaLibraryScanResponse expectedResponse = new(Guid.NewGuid(), request.Id); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + ScanLibraryRequest request = _scanLibraryRequestFixture.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_ShouldSendScanLibraryCommandToSender() + { + // Arrange + ScanLibraryRequest request = _scanLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new MediaLibraryScanResponse(Guid.NewGuid(), request.Id))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.Id == request.Id), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ScanLibraryRequest request = _scanLibraryRequestFixture.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(new MediaLibraryScanResponse(Guid.NewGuid(), request.Id)); + }, 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/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs new file mode 100644 index 00000000..d7e2d21d --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/Management/UpdateLibrary/UpdateLibraryEndpointTests.cs @@ -0,0 +1,142 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; +using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.Management; +using Lumina.Contracts.Requests.MediaLibrary.Management; +using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.Management.UpdateLibrary; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Management.UpdateLibrary; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateLibraryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdateLibraryEndpoint _sut; + private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); + private readonly LibraryResponseFixture _libraryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdateLibraryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryResponse() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + LibraryResponse expectedResponse = _libraryResponseFixture.Create(id: request.Id, userId: request.UserId); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.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_ShouldSendUpdateLibraryCommandToSender() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Id == request.Id && + command.OwnerId == request.UserId && + command.Title == request.Title && + command.LibraryType == request.LibraryType && + command.ContentLocations == request.ContentLocations && + command.CoverImage == request.CoverImage && + command.IsEnabled == request.IsEnabled && + command.IsLocked == request.IsLocked && + command.DownloadMetadataFromWeb == request.DownloadMetadataFromWeb && + command.ShouldSaveMetadataInMediaDirectories == request.ShouldSaveMetadataInMediaDirectories && + command.ShouldSkipUnchangedDirectoriesDuringScan == request.ShouldSkipUnchangedDirectoriesDuringScan), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + UpdateLibraryRequest request = _updateLibraryRequestFixture.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(_libraryResponseFixture.Create(id: request.Id, userId: request.UserId)); + }, 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/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs new file mode 100644 index 00000000..a0bd0b67 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetBook/GetBookEndpointTests.cs @@ -0,0 +1,36 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetBook; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetBookEndpointTests +{ + private readonly GetBookEndpoint _sut = Factory.Create(); + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResult() + { + // Arrange + GetBookRequest request = new(Guid.NewGuid().ToString()); + CancellationToken cancellationToken = CancellationToken.None; + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Assert.IsType(result); + } +} 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 8e223f1a..508ab4b6 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 @@ -4,6 +4,7 @@ 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.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.Common; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; @@ -32,6 +33,7 @@ public class GetBooksEndpointTests private readonly IQueryHandler>> _mockHandler; private readonly GetBooksEndpoint _sut; private readonly GetBooksRequestFixture _getBooksRequestFixture = new(); + private readonly BookResponseFixture _bookResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -48,7 +50,7 @@ public class GetBooksEndpointTests // Arrange GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PaginatedResponse expectedResponse = CreatePaginatedResponse(bookCount: 2); + PaginatedResponse expectedResponse = CreatePaginatedResponse(bookCount: 2, _bookResponseFixture); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -119,7 +121,7 @@ public class GetBooksEndpointTests GetBooksRequest request = _getBooksRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(CreatePaginatedResponse(bookCount: 0))); + .Returns(Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -151,7 +153,7 @@ public class GetBooksEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(CreatePaginatedResponse(bookCount: 0)); + return Result.From(CreatePaginatedResponse(bookCount: 0, _bookResponseFixture)); }, callInfo.Arg())); // Act @@ -169,11 +171,11 @@ 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) + private static PaginatedResponse CreatePaginatedResponse(int bookCount, BookResponseFixture bookResponseFixture) { List books = []; for (int index = 0; index < bookCount; index++) - books.Add(CreateBookResponse()); + books.Add(bookResponseFixture.Create()); return new PaginatedResponse { @@ -184,50 +186,4 @@ public class GetBooksEndpointTests NumberOfPages = bookCount > 0 ? 1 : 0 }; } - - /// - /// Creates a minimal valid . - /// - /// A configured book response instance. - private static BookResponse CreateBookResponse() - { - return new BookResponse( - Id: Guid.NewGuid(), - 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, - MetadataStatus: MetadataStatus.Pending, - LastMetadataUpdateUtc: null, - MetadataProvider: null, - CreatedOnUtc: DateTime.UtcNow, - UpdatedOnUtc: null - ); - } } diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs new file mode 100644 index 00000000..4de4c94c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Maintenance/CheckHealthEndpointTests.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Api.Core.Endpoints.Maintenance; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Maintenance; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CheckHealthEndpointTests +{ + private readonly CheckHealthEndpoint _sut = Factory.Create(); + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldReturnOkResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Assert.IsType(result); + } +} 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 new file mode 100644 index 00000000..84542ef6 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,134 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; +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.GetLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryMetadataProvidersEndpoint _sut; + private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryMetadataProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryMetadataProviderResponses() + { + // Arrange + GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponses = + [ + new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider A", true, 1), + new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider B", false, 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 + GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.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_ShouldSendGetLibraryMetadataProvidersQueryToSender() + { + // Arrange + GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.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 + GetLibraryMetadataProvidersRequest request = _getLibraryMetadataProvidersRequestFixture.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/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs new file mode 100644 index 00000000..d91e3728 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; +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.GetPluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetPluginSettingsEndpoint _sut; + private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPluginSettingsResponse() + { + // Arrange + GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PluginSettingsResponse expectedResponse = new( + PluginId: request.PluginId, + Schema: [], + Settings: null + ); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Plugin.NotFound", "The requested plugin 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("Plugin.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested plugin 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_ShouldSendGetPluginSettingsQueryToSender() + { + // Arrange + GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(new PluginSettingsResponse(request.PluginId, [], null))); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.PluginId == request.PluginId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.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(new PluginSettingsResponse(request.PluginId, [], null)); + }, 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/GetPlugins/GetPluginsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs new file mode 100644 index 00000000..416e7f6b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPlugins/GetPluginsEndpointTests.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetPlugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPlugins; +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.GetPlugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginsEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetPluginsEndpoint _sut; + private readonly PluginResponseFixture _pluginResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPluginsEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPluginResponses() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponses = [_pluginResponseFixture.Create(), _pluginResponseFixture.Create()]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("Plugin.GetPlugins.Failed", "Failed to get the plugins."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Plugin.GetPlugins.Failed", problemDetails.ProblemDetails.Title); + Assert.Equal("Failed to get the plugins.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPluginsQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync(Arg.Any(), Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + 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>([_pluginResponseFixture.Create()]); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, 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/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs new file mode 100644 index 00000000..88b8e0d3 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; +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.ReorderLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ReorderLibraryMetadataProvidersEndpoint _sut; + private readonly ReorderLibraryMetadataProvidersRequestFixture _reorderLibraryMetadataProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryMetadataProvidersEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.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 + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata 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("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The metadata 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_ShouldSendReorderLibraryMetadataProvidersCommandToSender() + { + // Arrange + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.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 + ReorderLibraryMetadataProvidersRequest request = _reorderLibraryMetadataProvidersRequestFixture.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/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..f357a42c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; +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.SetLibraryMetadataProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly SetLibraryMetadataProviderEnabledEndpoint _sut; + private readonly SetLibraryMetadataProviderEnabledRequestFixture _setLibraryMetadataProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryMetadataProviderEnabledEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.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 + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryMetadataProviderConfiguration.NotFound", "The metadata 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("LibraryMetadataProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The metadata 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_ShouldSendSetLibraryMetadataProviderEnabledCommandToSender() + { + // Arrange + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.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 + SetLibraryMetadataProviderEnabledRequest request = _setLibraryMetadataProviderEnabledRequestFixture.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/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs new file mode 100644 index 00000000..5a44c4ff --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -0,0 +1,128 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.UpdatePluginSettings; +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.UpdatePluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePluginSettingsEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdatePluginSettingsEndpoint _sut; + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePluginSettingsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.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 + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Plugin.NotFound", "The requested plugin 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("Plugin.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested plugin 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_ShouldSendUpdatePluginSettingsCommandToSender() + { + // Arrange + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.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.PluginId == request.PluginId && + command.Settings == request.Settings), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.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); + } +}